promiscuity/microservices/Auth/Services/BlacklistService.cs

37 lines
1.3 KiB
C#

using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace Auth.Services;
public class BlacklistedToken
{
[BsonId] public string Jti { get; set; } = default!;
public DateTime ExpiresAt { get; set; }
}
public class BlacklistService
{
private readonly IMongoCollection<BlacklistedToken> _col;
public BlacklistService(IConfiguration cfg)
{
var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017";
var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb";
var client = new MongoClient(cs);
var db = client.GetDatabase(dbName);
_col = db.GetCollection<BlacklistedToken>("BlacklistedTokens");
// TTL index so revocations expire automatically
var keys = Builders<BlacklistedToken>.IndexKeys.Ascending(x => x.ExpiresAt);
_col.Indexes.CreateOne(new CreateIndexModel<BlacklistedToken>(keys, new CreateIndexOptions { ExpireAfter = TimeSpan.Zero }));
}
public Task AddToBlacklistAsync(string jti, DateTime expiresAt) =>
_col.ReplaceOneAsync(x => x.Jti == jti,
new BlacklistedToken { Jti = jti, ExpiresAt = expiresAt },
new ReplaceOptions { IsUpsert = true });
public Task<bool> IsBlacklistedAsync(string jti) =>
_col.Find(x => x.Jti == jti).AnyAsync();
}