diff --git a/.gitignore b/.gitignore index d6c07e0..e309cc6 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,10 @@ bld/ # Visual Studio 2015/2017 cache/options directory .vs/ + +# JetBrains Rider cache/options/config directory +.idea + # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ diff --git a/Revoke.NET.Akavache/AkavacheBlackList.cs b/Revoke.NET.Akavache/AkavacheBlackList.cs index 0bb827c..d1c0ba2 100644 --- a/Revoke.NET.Akavache/AkavacheBlackList.cs +++ b/Revoke.NET.Akavache/AkavacheBlackList.cs @@ -1,103 +1,102 @@ -using System; -using System.Collections.Generic; +namespace Revoke.NET.Akavache; + +using System; using System.Reactive.Linq; using System.Threading.Tasks; -using Akavache; -using Registrations = Akavache.Registrations; +using global::Akavache; -namespace Revoke.NET.Akavache +public class AkavacheBlackList : IBlackList { - public class AkavacheBlackList : IBlackList + private static TimeSpan? _defaultTtl; + private readonly IBlobCache _blackList; + + private AkavacheBlackList(IBlobCache blobcache) { - private readonly IBlobCache _blackList; - private static TimeSpan? _defaultTtl; + this._blackList = blobcache; + } - private AkavacheBlackList(IBlobCache blobcache) + public async Task Delete(string key) + { + try { - this._blackList = blobcache; - } + await this._blackList.Invalidate(key); - public static async Task CreateStoreAsync(string cacheName, IBlobCache blobCache, - TimeSpan? defaultTtl = null) + return true; + } + catch { - _defaultTtl = defaultTtl; - Registrations.Start(cacheName); - await blobCache.Vacuum(); - return new AkavacheBlackList(blobCache); + return false; } + } + public async Task DeleteAll() + { + await this._blackList.InvalidateAll(); + } - public async Task Delete(string key) + public async Task IsRevoked(string key) + { + try { - try - { - await _blackList.Invalidate(key); - return true; - } - catch - { - return false; - } - } + await this._blackList.Vacuum(); + var exist = await this._blackList.Get(key); - public async Task DeleteAll() + return exist.Length > 0; + } + catch { - await _blackList.InvalidateAll(); + return false; } + } - public async Task IsRevoked(string key) + public async Task Revoke(string key) + { + try { - try - { - await _blackList.Vacuum(); - var exist = await _blackList.Get(key); - return exist.Length > 0; - } - catch - { - return false; - } - } + await this._blackList.InsertObject(key, key, DateTimeOffset.Now.Add(_defaultTtl ?? TimeSpan.MaxValue)); - public async Task Revoke(string key) + return true; + } + catch { - try - { - await _blackList.InsertObject(key, key, DateTimeOffset.Now.Add(_defaultTtl ?? TimeSpan.MaxValue)); - return true; - } - catch - { - return false; - } + return false; } + } + + public async Task Revoke(string key, TimeSpan expireAfter) + { + try + { + await this._blackList.InsertObject(key, key, DateTimeOffset.Now.Add(expireAfter)); - public async Task Revoke(string key, TimeSpan expireAfter) + return true; + } + catch { - try - { - await _blackList.InsertObject(key, key, DateTimeOffset.Now.Add(expireAfter)); - - return true; - } - catch - { - return false; - } + return false; } + } - public async Task Revoke(string key, DateTime expireOn) + public async Task Revoke(string key, DateTime expireOn) + { + try { - try - { - await _blackList.InsertObject(key, key, expireOn); - - return true; - } - catch - { - return false; - } + await this._blackList.InsertObject(key, key, expireOn); + + return true; + } + catch + { + return false; } } + + public static async Task CreateStoreAsync(string cacheName, IBlobCache blobCache, TimeSpan? defaultTtl = null) + { + _defaultTtl = defaultTtl; + Registrations.Start(cacheName); + await blobCache.Vacuum(); + + return new AkavacheBlackList(blobCache); + } } \ No newline at end of file diff --git a/Revoke.NET.Akavache/README.md b/Revoke.NET.Akavache/README.md index 8c4c345..c560bf9 100644 --- a/Revoke.NET.Akavache/README.md +++ b/Revoke.NET.Akavache/README.md @@ -1,13 +1,17 @@ # Revoke.NET Akavache Store + Akavache BlackList Store Extension for [`Revoke.NET`] (https://www.nuget.org/packages/Revoke.NET) # Installation + Install the `Revoke.NET.Akavache` [NuGet package](https://www.nuget.org/packages/Revoke.NET.Akavache) into your app + ```powershell PM> Install-Package Revoke.NET.Akavache ``` # How to use + ```csharp using Revoke.NET; using Revoke.NET.Akavache; @@ -27,7 +31,9 @@ await store.Delete(key); // Delete a key from blacklist ``` # Usage with ASP.NET Core + Install the `Revoke.NET.AspNetCore` [NuGet package](https://www.nuget.org/packages/Revoke.NET.AspNetCore) + ```powershell PM> Install-Package Revoke.NET.AspNetCore ``` diff --git a/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj b/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj index 2792eaf..1de1484 100644 --- a/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj +++ b/Revoke.NET.Akavache/Revoke.NET.Akavache.csproj @@ -1,39 +1,39 @@  - - netstandard2.0 - 10.0 - revoke.net.png - readme.md - LICENSE - Library - 2.0.0 - - Chakhoum Ahmed (github.com/rainxh11) - Revoke.NET Akavache Store Extension - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.Akavache - github - true - revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;mongodb;store - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - False - True - + + netstandard2.0 + 10.0 + revoke.net.png + readme.md + LICENSE + Library + 2.0.0 + + Chakhoum Ahmed (github.com/rainxh11) + Revoke.NET Akavache Store Extension + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.Akavache + github + true + revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;mongodb;store + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + False + True + - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/Revoke.NET.Akavache/RevokeService.cs b/Revoke.NET.Akavache/RevokeService.cs index 1453872..a23439d 100644 --- a/Revoke.NET.Akavache/RevokeService.cs +++ b/Revoke.NET.Akavache/RevokeService.cs @@ -1,39 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Revoke.NET.Akavache; + +using System; +using global::Akavache; using Microsoft.Extensions.DependencyInjection; -using Akavache; -namespace Revoke.NET.Akavache +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddRevokeAkavacheSQLiteStore(this IServiceCollection services) { - public static IServiceCollection AddRevokeAkavacheSQLiteStore(this IServiceCollection services) - { - return services - .AddSingleton(provider => AkavacheBlackList - .CreateStoreAsync("RevokeStore", BlobCache.LocalMachine) - .GetAwaiter() - .GetResult()); - } + return services.AddSingleton( + provider => AkavacheBlackList.CreateStoreAsync("RevokeStore", BlobCache.LocalMachine) + .GetAwaiter() + .GetResult()); + } - public static IServiceCollection AddRevokeAkavacheInMemoryStore(this IServiceCollection services) - { - return services - .AddSingleton(provider => AkavacheBlackList - .CreateStoreAsync("RevokeStore", BlobCache.InMemory) - .GetAwaiter() - .GetResult()); - } + public static IServiceCollection AddRevokeAkavacheInMemoryStore(this IServiceCollection services) + { + return services.AddSingleton( + provider => AkavacheBlackList.CreateStoreAsync("RevokeStore", BlobCache.InMemory) + .GetAwaiter() + .GetResult()); + } - public static IServiceCollection AddRevokeAkavacheStore(this IServiceCollection services, - Func configBlobCache) - { - return services - .AddSingleton(provider => AkavacheBlackList - .CreateStoreAsync("RevokeStore", configBlobCache(provider)) - .GetAwaiter() - .GetResult()); - } + public static IServiceCollection AddRevokeAkavacheStore(this IServiceCollection services, Func configBlobCache) + { + return services.AddSingleton( + provider => AkavacheBlackList.CreateStoreAsync("RevokeStore", configBlobCache(provider)) + .GetAwaiter() + .GetResult()); } } \ No newline at end of file diff --git a/Revoke.NET.AspNetCore/README.md b/Revoke.NET.AspNetCore/README.md index 9b2364d..7e7ff7a 100644 --- a/Revoke.NET.AspNetCore/README.md +++ b/Revoke.NET.AspNetCore/README.md @@ -1,13 +1,17 @@ # Revoke.NET ASP.NET Core Extension + MongoDB BlackList Store Extension for [`Revoke.NET`] (https://www.nuget.org/packages/Revoke.NET) # Installation + Install the `Revoke.NET.AspNetCore` [NuGet package](https://www.nuget.org/packages/Revoke.NET.AspNetCore) into your app + ```powershell PM> Install-Package Revoke.NET.AspNetCore ``` # Usage with ASP.NET Core + ```csharp using Revoke.NET; using Revoke.NET.AspNetCore; @@ -23,6 +27,7 @@ builder.Services ``` ### JWT Bearer Token Example + ```csharp using System.Net.Http.Headers; using Microsoft.AspNetCore.Mvc; diff --git a/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj b/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj index f43ebe7..687fee1 100644 --- a/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj +++ b/Revoke.NET.AspNetCore/Revoke.NET.AspNetCore.csproj @@ -1,40 +1,40 @@ - - netstandard2.1 - 10.0 - revoke.net.png - readme.md - LICENSE - Library - 2.0.0 - - Chakhoum Ahmed (github.com/rainxh11) - Revoke.NET ASP.NET Core Extension - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.AspNetCore - github - true - revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - annotations - True - - - - - - - - - - - - - - - - + + netstandard2.1 + 10.0 + revoke.net.png + readme.md + LICENSE + Library + 2.0.0 + + Chakhoum Ahmed (github.com/rainxh11) + Revoke.NET ASP.NET Core Extension + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.AspNetCore + github + true + revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + annotations + True + + + + + + + + + + + + + + + + diff --git a/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs b/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs index d858d4f..4c73e80 100644 --- a/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs +++ b/Revoke.NET.AspNetCore/RevokeHttpMiddleware.cs @@ -1,93 +1,85 @@ -using System; -using System.Collections.Generic; -using System.Linq; +namespace Revoke.NET.AspNetCore; + +using System; using System.Net; -using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -namespace Revoke.NET.AspNetCore +public class RevokeHttpMiddleware : IMiddleware { - public class RevokeHttpMiddleware : IMiddleware - { - private readonly IBlackList store; - private readonly Func selector; + private readonly IBlackList store; + private readonly Func selector; #nullable enable - private readonly ILogger? logger; - private Func>? responseFunc; + private readonly ILogger? logger; + private readonly Func>? responseFunc; #nullable disable - public RevokeHttpMiddleware(IBlackList store, ILogger logger, - Func selector) - { - this.store = store; - this.logger = logger; - this.selector = selector; - } - - public RevokeHttpMiddleware(IBlackList store, Func selector) - { - this.store = store; - this.selector = selector; - } + public RevokeHttpMiddleware(IBlackList store, ILogger logger, Func selector) + { + this.store = store; + this.logger = logger; + this.selector = selector; + } - public RevokeHttpMiddleware(IBlackList store, ILogger logger, - Func selector, Func> responseFunc) - { - this.store = store; - this.logger = logger; - this.selector = selector; - this.responseFunc = responseFunc; - } + public RevokeHttpMiddleware(IBlackList store, Func selector) + { + this.store = store; + this.selector = selector; + } - public RevokeHttpMiddleware(IBlackList store, Func selector, - Func> responseFunc) - { - this.store = store; - this.selector = selector; - this.responseFunc = responseFunc; - } + public RevokeHttpMiddleware( + IBlackList store, ILogger logger, Func selector, + Func> responseFunc) + { + this.store = store; + this.logger = logger; + this.selector = selector; + this.responseFunc = responseFunc; + } + public RevokeHttpMiddleware(IBlackList store, Func selector, Func> responseFunc) + { + this.store = store; + this.selector = selector; + this.responseFunc = responseFunc; + } - public async Task InvokeAsync(HttpContext context, RequestDelegate next) + public async Task InvokeAsync(HttpContext context, RequestDelegate next) + { + try { - try + var revokeKey = this.selector(context); + if (revokeKey != null) { - var revokeKey = selector(context); - if (revokeKey != null) + if (await this.store.IsRevoked(revokeKey)) { - if (await store.IsRevoked(revokeKey)) + if (this.responseFunc != null) { - if (responseFunc != null) - { - await responseFunc(context.Response); - } - else - { - context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; - } - - - logger.LogInformation( - $"[Revoke.NET] Revoked Access to key: '{revokeKey}'"); + await this.responseFunc(context.Response); } else { - await next(context); + context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; } + + this.logger.LogInformation($"[Revoke.NET] Revoked Access to key: '{revokeKey}'"); } else { await next(context); } } - catch (Exception ex) + else { - logger?.LogError(ex.Message); await next(context); } } + catch (Exception ex) + { + this.logger?.LogError(ex.Message); + await next(context); + } } } \ No newline at end of file diff --git a/Revoke.NET.AspNetCore/RevokeService.cs b/Revoke.NET.AspNetCore/RevokeService.cs index de743f5..c8be29e 100644 --- a/Revoke.NET.AspNetCore/RevokeService.cs +++ b/Revoke.NET.AspNetCore/RevokeService.cs @@ -1,189 +1,201 @@ -using System; -using System.Collections.Generic; +namespace Revoke.NET.AspNetCore; + +using System; using System.Net.Http.Headers; -using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; -namespace Revoke.NET.AspNetCore +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, Func selector) { - public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, - Func selector) - { - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, selector); - }); - } - - /// - /// Register a Revoke Http Middleware with a Custom Value Selector from an HttpContext - /// - /// - /// Selector function that returns a key to determine if request will be denied, null/empty values to skip - /// custom response function - /// - public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, - Func selector, Func> responseFunc) - { - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, selector, responseFunc); - }); - } - - /// - /// Register a Revoke Http Middleware with default JWT Bearer Token Selector 'Authorization : Bearer %TOKEN%' - /// - /// - /// - public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services) - { - var bearerTokenSelector = new Func(context => + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, selector); + }); + } + + /// + /// Register a Revoke Http Middleware with a Custom Value Selector from an HttpContext + /// + /// + /// + /// Selector function that returns a key to determine if request will be denied, null/empty values + /// to skip + /// + /// custom response function + /// + public static IServiceCollection AddHttpContextRevokeMiddleware(this IServiceCollection services, Func selector, Func> responseFunc) + { + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, selector, responseFunc); + }); + } + + /// + /// Register a Revoke Http Middleware with default JWT Bearer Token Selector 'Authorization : Bearer %TOKEN%' + /// + /// + /// + public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services) + { + var bearerTokenSelector = new Func( + context => { if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) { - var jwtToken = AuthenticationHeaderValue.Parse(authHeader).Parameter; - if (jwtToken != null) return jwtToken; + var jwtToken = AuthenticationHeaderValue.Parse(authHeader) + .Parameter; + if (jwtToken != null) + { + return jwtToken; + } } return null; }); - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, bearerTokenSelector); - }); - } - - /// - /// Register a Revoke Http Middleware with default JWT Bearer Token Selector 'Authorization : Bearer %TOKEN%' - /// - /// - /// custom response function - /// - public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services, - Func> responseFunc) - { - var bearerTokenSelector = new Func(context => + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, bearerTokenSelector); + }); + } + + /// + /// Register a Revoke Http Middleware with default JWT Bearer Token Selector 'Authorization : Bearer %TOKEN%' + /// + /// + /// custom response function + /// + public static IServiceCollection AddJWTBearerTokenRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + { + var bearerTokenSelector = new Func( + context => { if (context.Request.Headers.TryGetValue("Authorization", out var authHeader)) { - var jwtToken = AuthenticationHeaderValue.Parse(authHeader).Parameter; - if (jwtToken != null) return jwtToken; + var jwtToken = AuthenticationHeaderValue.Parse(authHeader) + .Parameter; + if (jwtToken != null) + { + return jwtToken; + } } return null; }); - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, bearerTokenSelector, responseFunc); - }); - } - - /// - /// Register a Revoke Http Middleware with IP/Host selector - /// - /// - /// - public static IServiceCollection AddIPRevokeMiddleware(this IServiceCollection services) - { - var ipSelector = new Func(context => context.Request.Host.Host); - - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, ipSelector); - }); - } - - /// - /// Register a Revoke Http Middleware with IP/Host selector - /// - /// - /// custom response function - /// - public static IServiceCollection AddIPRevokeMiddleware(this IServiceCollection services, - Func> responseFunc) - { - var ipSelector = new Func(context => context.Request.Host.Host); - - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); - }); - } - - /// - /// Register a Revoke Http Middleware with User ID selector - /// - /// - /// - public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services) - { - var ipSelector = new Func(context => context.Request.Host.Host); - - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, ipSelector); - }); - } - - /// - /// Register a Revoke Http Middleware with User ID selector - /// - /// - /// custom response function - /// - public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services, - Func> responseFunc) - { - var ipSelector = new Func(context => context.Request.Host.Host); - - return services - .AddSingleton(provider => - { - var store = provider.GetService(); - var logger = provider.GetService>(); - return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); - }); - } - - /// - /// Use Revoke Http Middleware - /// - /// - /// - public static IApplicationBuilder UseRevoke(this IApplicationBuilder builder) - { - return builder - .UseMiddleware(); - } + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, bearerTokenSelector, responseFunc); + }); + } + + /// + /// Register a Revoke Http Middleware with IP/Host selector + /// + /// + /// + public static IServiceCollection AddIPRevokeMiddleware(this IServiceCollection services) + { + var ipSelector = new Func(context => context.Request.Host.Host); + + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, ipSelector); + }); + } + + /// + /// Register a Revoke Http Middleware with IP/Host selector + /// + /// + /// custom response function + /// + public static IServiceCollection AddIPRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + { + var ipSelector = new Func(context => context.Request.Host.Host); + + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); + }); + } + + /// + /// Register a Revoke Http Middleware with User ID selector + /// + /// + /// + public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services) + { + var ipSelector = new Func(context => context.Request.Host.Host); + + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, ipSelector); + }); + } + + /// + /// Register a Revoke Http Middleware with User ID selector + /// + /// + /// custom response function + /// + public static IServiceCollection AddUserIdRevokeMiddleware(this IServiceCollection services, Func> responseFunc) + { + var ipSelector = new Func(context => context.Request.Host.Host); + + return services.AddSingleton( + provider => + { + var store = provider.GetService(); + var logger = provider.GetService>(); + + return new RevokeHttpMiddleware(store, logger, ipSelector, responseFunc); + }); + } + + /// + /// Use Revoke Http Middleware + /// + /// + /// + public static IApplicationBuilder UseRevoke(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); } } \ No newline at end of file diff --git a/Revoke.NET.EasyCaching/EasyCachingBlackList.cs b/Revoke.NET.EasyCaching/EasyCachingBlackList.cs index bb07317..997c4ad 100644 --- a/Revoke.NET.EasyCaching/EasyCachingBlackList.cs +++ b/Revoke.NET.EasyCaching/EasyCachingBlackList.cs @@ -1,27 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using EasyCaching.Core; +namespace Revoke.NET.EasyCaching; -namespace Revoke.NET.EasyCaching; +using System; +using System.Threading.Tasks; +using global::EasyCaching.Core; internal class EasyCachingBlackList : IBlackList { - private readonly IEasyCachingProvider _easyCaching; private readonly TimeSpan? _defaultTtl; + private readonly IEasyCachingProvider _easyCaching; public EasyCachingBlackList(IEasyCachingProvider easyCaching, TimeSpan? defaultTtl = null) { - _defaultTtl = defaultTtl; - _easyCaching = easyCaching; + this._defaultTtl = defaultTtl; + this._easyCaching = easyCaching; } public async Task Revoke(string key, TimeSpan expireAfter) { try { - await _easyCaching.SetAsync(key, key, expireAfter); + await this._easyCaching.SetAsync(key, key, expireAfter); + return true; } catch @@ -34,7 +33,8 @@ public async Task Revoke(string key, DateTime expireOn) { try { - await _easyCaching.SetAsync(key, key, expireOn - DateTime.Now); + await this._easyCaching.SetAsync(key, key, expireOn - DateTime.Now); + return true; } catch @@ -47,7 +47,8 @@ public async Task Revoke(string key) { try { - await _easyCaching.SetAsync(key, key, _defaultTtl ?? TimeSpan.MaxValue); + await this._easyCaching.SetAsync(key, key, this._defaultTtl ?? TimeSpan.MaxValue); + return true; } catch @@ -60,7 +61,8 @@ public async Task Delete(string key) { try { - await _easyCaching.RemoveAsync(key); + await this._easyCaching.RemoveAsync(key); + return true; } catch @@ -73,7 +75,7 @@ public async Task DeleteAll() { try { - await _easyCaching.FlushAsync(); + await this._easyCaching.FlushAsync(); } catch { @@ -84,7 +86,7 @@ public async Task IsRevoked(string key) { try { - return await _easyCaching.ExistsAsync(key); + return await this._easyCaching.ExistsAsync(key); } catch { diff --git a/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj b/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj index db04b9e..2c885a4 100644 --- a/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj +++ b/Revoke.NET.EasyCaching/Revoke.NET.EasyCaching.csproj @@ -1,39 +1,39 @@  - - netstandard2.0 - 10.0 - revoke.net.png - LICENSE - Library - 2.0.0 - - Chakhoum Ahmed (github.com/rainxh11) - Revoke.NET EasyCaching Store Extension - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.EasyCaching - github - true - revoke;easycaching;permission;deny;blacklist;expiration;invalidate;store - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - False - True - + + netstandard2.0 + 10.0 + revoke.net.png + LICENSE + Library + 2.0.0 + + Chakhoum Ahmed (github.com/rainxh11) + Revoke.NET EasyCaching Store Extension + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.EasyCaching + github + true + revoke;easycaching;permission;deny;blacklist;expiration;invalidate;store + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + False + True + - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/Revoke.NET.EasyCaching/RevokeService.cs b/Revoke.NET.EasyCaching/RevokeService.cs index a0f5256..a046c2d 100644 --- a/Revoke.NET.EasyCaching/RevokeService.cs +++ b/Revoke.NET.EasyCaching/RevokeService.cs @@ -1,43 +1,35 @@ -using System; -using System.Collections.Generic; -using System.Text; -using EasyCaching.Core; +namespace Revoke.NET.EasyCaching; + +using System; +using global::EasyCaching.Core; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Revoke.NET.EasyCaching; -namespace Revoke.NET.EasyCaching +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, IEasyCachingProvider easyCachingProvider, TimeSpan? defaultTtl = null) + { + return services.AddSingleton(provider => new EasyCachingBlackList(easyCachingProvider, defaultTtl)); + } + + public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, Func easyCachingConfig, TimeSpan? defaultTtl = null) { - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, - IEasyCachingProvider easyCachingProvider, TimeSpan? defaultTtl = null) - { - return services - .AddSingleton(provider => - new EasyCachingBlackList(easyCachingProvider, defaultTtl)); - } + return services.AddSingleton( + provider => + { + var factory = provider.GetService(); - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, - Func easyCachingConfig, TimeSpan? defaultTtl = null) - { - return services - .AddSingleton(provider => - { - var factory = provider.GetService(); - return new EasyCachingBlackList(easyCachingConfig?.Invoke(factory), defaultTtl); - }); - } + return new EasyCachingBlackList(easyCachingConfig?.Invoke(factory), defaultTtl); + }); + } + + public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, TimeSpan? defaultTtl = null) + { + return services.AddSingleton( + provider => + { + var easyCachingProvider = provider.GetService(); - public static IServiceCollection AddRevokeEasyCaching(this IServiceCollection services, - TimeSpan? defaultTtl = null) - { - return services - .AddSingleton(provider => - { - var easyCachingProvider = provider.GetService(); - return new EasyCachingBlackList(easyCachingProvider, defaultTtl); - }); - } + return new EasyCachingBlackList(easyCachingProvider, defaultTtl); + }); } } \ No newline at end of file diff --git a/Revoke.NET.MinimalAPIExample/Program.cs b/Revoke.NET.MinimalAPIExample/Program.cs index 635b70d..5c6cfed 100644 --- a/Revoke.NET.MinimalAPIExample/Program.cs +++ b/Revoke.NET.MinimalAPIExample/Program.cs @@ -5,8 +5,7 @@ var builder = WebApplication.CreateBuilder(args); -builder.Services - .AddRevokeInMemoryStore() // Register a Revoke Store +builder.Services.AddRevokeInMemoryStore() // Register a Revoke Store .AddJWTBearerTokenRevokeMiddleware(); // Register a Revoke Middleware var app = builder.Build(); @@ -16,13 +15,16 @@ app.UseAuthorization(); app.UseAuthentication(); -app.MapGet("/logout", async ([FromServices] IBlackList store, HttpRequest request) => -{ - var token = AuthenticationHeaderValue.Parse(request.Headers.Authorization).Parameter; +app.MapGet( + "/logout", + async ([FromServices] IBlackList store, HttpRequest request) => + { + var token = AuthenticationHeaderValue.Parse(request.Headers.Authorization) + .Parameter; - await store.Revoke(token); + await store.Revoke(token); - return true; -}); + return true; + }); app.Run(); \ No newline at end of file diff --git a/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj b/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj index 38b9831..ca97af9 100644 --- a/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj +++ b/Revoke.NET.MinimalAPIExample/Revoke.NET.MinimalAPIExample.csproj @@ -1,17 +1,17 @@  - - net6.0 - enable - enable - + + net6.0 + enable + enable + - - - - - - - + + + + + + + diff --git a/Revoke.NET.MongoDB/MongoBlackList.cs b/Revoke.NET.MongoDB/MongoBlackList.cs index 9c46c40..3e61242 100644 --- a/Revoke.NET.MongoDB/MongoBlackList.cs +++ b/Revoke.NET.MongoDB/MongoBlackList.cs @@ -1,131 +1,143 @@ -using System; -using System.Collections.Generic; +namespace Revoke.NET.MongoDB; + +using System; using System.Threading.Tasks; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Attributes; -using MongoDB.Driver; -using Revoke.NET; +using global::MongoDB.Bson; +using global::MongoDB.Bson.Serialization.Attributes; +using global::MongoDB.Driver; -namespace Revoke.NET.MongoDB +public class MongoBlackListItem { - public class MongoBlackListItem + public MongoBlackListItem(string key, DateTime expireOn) { - [BsonId] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); + this.Key = key; + this.ExpireOn = expireOn; + } - public MongoBlackListItem(string key, DateTime expireOn) - { - Key = key; - ExpireOn = expireOn; - } + [BsonId] + public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); + + public string Key { get; set; } + public DateTime ExpireOn { get; set; } +} - public string Key { get; set; } - public DateTime ExpireOn { get; set; } +public class MongoBlackList : IBlackList +{ + private readonly IMongoCollection _blacklist; + + private MongoBlackList(IMongoCollection blacklist) + { + this._blacklist = blacklist; } - public class MongoBlackList : IBlackList + public async Task Revoke(string key, TimeSpan expireAfter) { - private readonly IMongoCollection _blacklist; + try + { + await this._blacklist.InsertOneAsync(new MongoBlackListItem(key, DateTime.Now.Add(expireAfter))); - private MongoBlackList(IMongoCollection blacklist) + return true; + } + catch { - this._blacklist = blacklist; + return false; } + } - public static async Task CreateStoreAsync(string dbName, - MongoClientSettings clientSettings) + public async Task Revoke(string key, DateTime expireOn) + { + try { - var client = new MongoClient(clientSettings); - - var db = client.GetDatabase(dbName); - - var keyIndex = Builders.IndexKeys.Ascending(x => x.Key); - var ttlIndex = Builders.IndexKeys.Ascending(x => x.ExpireOn); + await this._blacklist.InsertOneAsync(new MongoBlackListItem(key, expireOn)); - var collection = db.GetCollection(nameof(MongoBlackListItem)); + return true; + } + catch + { + return false; + } + } - await collection.Indexes.CreateOneAsync( - new CreateIndexModel(keyIndex, new CreateIndexOptions() { Unique = true })); - await collection.Indexes.CreateOneAsync( - new CreateIndexModel(ttlIndex, - new CreateIndexOptions() { ExpireAfter = TimeSpan.FromMinutes(1) })); + public async Task Revoke(string key) + { + try + { + await this._blacklist.InsertOneAsync(new MongoBlackListItem(key, DateTime.MaxValue)); - return new MongoBlackList(collection); + return true; } - - public async Task Revoke(string key, TimeSpan expireAfter) + catch { - try - { - await _blacklist.InsertOneAsync(new MongoBlackListItem(key, DateTime.Now.Add(expireAfter))); - return true; - } - catch - { - return false; - } + return false; } + } - public async Task Revoke(string key, DateTime expireOn) + public async Task Delete(string key) + { + try { - try - { - await _blacklist.InsertOneAsync(new MongoBlackListItem(key, expireOn)); - return true; - } - catch - { - return false; - } - } + var delete = await this._blacklist.DeleteOneAsync(x => x.Key == key); - public async Task Revoke(string key) + return delete.IsAcknowledged; + } + catch { - try - { - await _blacklist.InsertOneAsync(new MongoBlackListItem(key, DateTime.MaxValue)); - return true; - } - catch - { - return false; - } + return false; } + } - public async Task Delete(string key) + public async Task DeleteAll() + { + try { - try - { - var delete = await _blacklist.DeleteOneAsync(x => x.Key == key); - return delete.IsAcknowledged; - } - catch - { - return false; - } + await this._blacklist.DeleteManyAsync(x => true); } - - public async Task DeleteAll() + catch { - try - { - await _blacklist.DeleteManyAsync(x => true); - } - catch - { - } } + } - public async Task IsRevoked(string key) + public async Task IsRevoked(string key) + { + try { - try - { - var item = await _blacklist.Find(x => x.Key == key).SingleAsync(); - return item.ExpireOn > DateTime.Now; - } - catch - { - return false; - } + var item = await this._blacklist.Find(x => x.Key == key) + .SingleAsync(); + + return item.ExpireOn > DateTime.Now; } + catch + { + return false; + } + } + + public static async Task CreateStoreAsync(string dbName, MongoClientSettings clientSettings) + { + var client = new MongoClient(clientSettings); + + var db = client.GetDatabase(dbName); + + var keyIndex = Builders.IndexKeys.Ascending(x => x.Key); + var ttlIndex = Builders.IndexKeys.Ascending(x => x.ExpireOn); + + var collection = db.GetCollection(nameof(MongoBlackListItem)); + + await collection.Indexes.CreateOneAsync( + new CreateIndexModel( + keyIndex, + new CreateIndexOptions + { + Unique = true + })); + await collection.Indexes.CreateOneAsync( + new CreateIndexModel( + ttlIndex, + new CreateIndexOptions + { + ExpireAfter = TimeSpan.FromMinutes(1) + })); + + return new MongoBlackList(collection); } } \ No newline at end of file diff --git a/Revoke.NET.MongoDB/README.md b/Revoke.NET.MongoDB/README.md index e9a3041..ca5d59d 100644 --- a/Revoke.NET.MongoDB/README.md +++ b/Revoke.NET.MongoDB/README.md @@ -1,13 +1,17 @@ # Revoke.NET MongoDB Store + MongoDB BlackList Store Extension for [`Revoke.NET`] (https://www.nuget.org/packages/Revoke.NET) # Installation + Install the `Revoke.NET.MongoDB` [NuGet package](https://www.nuget.org/packages/Revoke.NET.MongoDB) into your app + ```powershell PM> Install-Package Revoke.NET.MongoDB ``` # How to use + ```csharp using MongoDB.Driver; using Revoke.NET; @@ -26,7 +30,9 @@ await store.Delete(key); // Delete a key from blacklist ``` # Usage with ASP.NET Core + Install the `Revoke.NET.AspNetCore` [NuGet package](https://www.nuget.org/packages/Revoke.NET.AspNetCore) + ```powershell PM> Install-Package Revoke.NET.AspNetCore ``` diff --git a/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj b/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj index df0763d..59f9abf 100644 --- a/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj +++ b/Revoke.NET.MongoDB/Revoke.NET.MongoDB.csproj @@ -1,38 +1,38 @@  - - netstandard2.0 - 10.0 - revoke.net.png - readme.md - LICENSE - Library - 2.0.0 - - Chakhoum Ahmed (github.com/rainxh11) - Revoke.NET MongoDB Store Extension - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.MongoDB - github - true - revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;mongodb;store - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - True - + + netstandard2.0 + 10.0 + revoke.net.png + readme.md + LICENSE + Library + 2.0.0 + + Chakhoum Ahmed (github.com/rainxh11) + Revoke.NET MongoDB Store Extension + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.MongoDB + github + true + revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;mongodb;store + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + True + - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/Revoke.NET.MongoDB/RevokeService.cs b/Revoke.NET.MongoDB/RevokeService.cs index 8330fc7..bff615d 100644 --- a/Revoke.NET.MongoDB/RevokeService.cs +++ b/Revoke.NET.MongoDB/RevokeService.cs @@ -1,32 +1,23 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Revoke.NET.MongoDB; + +using global::MongoDB.Driver; using Microsoft.Extensions.DependencyInjection; -using MongoDB.Driver; -namespace Revoke.NET.MongoDB +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services) { - public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services) - { - return services - .AddSingleton(provider => MongoBlackList.CreateStoreAsync( - "RevokeStore", - MongoClientSettings.FromConnectionString("mongodb://127.0.0.1:27017/RevokeStore")) - .GetAwaiter() - .GetResult()); - } + return services.AddSingleton( + provider => MongoBlackList.CreateStoreAsync("RevokeStore", MongoClientSettings.FromConnectionString("mongodb://127.0.0.1:27017/RevokeStore")) + .GetAwaiter() + .GetResult()); + } - public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services, string dbName, - MongoClientSettings settings) - { - return services - .AddSingleton(provider => MongoBlackList.CreateStoreAsync( - dbName, - settings) - .GetAwaiter() - .GetResult()); - } + public static IServiceCollection AddRevokeMongoStore(this IServiceCollection services, string dbName, MongoClientSettings settings) + { + return services.AddSingleton( + provider => MongoBlackList.CreateStoreAsync(dbName, settings) + .GetAwaiter() + .GetResult()); } } \ No newline at end of file diff --git a/Revoke.NET.Redis/README.md b/Revoke.NET.Redis/README.md index 374dcf9..0dac899 100644 --- a/Revoke.NET.Redis/README.md +++ b/Revoke.NET.Redis/README.md @@ -1,13 +1,17 @@ # Revoke.NET Redis Store + Redis BlackList Store Extension for [`Revoke.NET`] (https://www.nuget.org/packages/Revoke.NET) # Installation + Install the `Revoke.NET.Redis` [NuGet package](https://www.nuget.org/packages/Revoke.NET.Redis) into your app + ```powershell PM> Install-Package Revoke.NET.Redis ``` # How to use + ```csharp using Revoke.NET; using Revoke.NET.Redis; @@ -24,7 +28,9 @@ await store.Delete(key); // Delete a key from blacklist ``` # Usage with ASP.NET Core + Install the `Revoke.NET.AspNetCore` [NuGet package](https://www.nuget.org/packages/Revoke.NET.AspNetCore) + ```powershell PM> Install-Package Revoke.NET.AspNetCore ``` diff --git a/Revoke.NET.Redis/RedisBlackList.cs b/Revoke.NET.Redis/RedisBlackList.cs index 9f5e5e8..1c9a6be 100644 --- a/Revoke.NET.Redis/RedisBlackList.cs +++ b/Revoke.NET.Redis/RedisBlackList.cs @@ -1,71 +1,74 @@ -using System; +namespace Revoke.NET.Redis; + +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using StackExchange.Redis; -using System.Text.Json; -namespace Revoke.NET.Redis +public class RedisBlackList : IBlackList { - public class RedisBlackList : IBlackList + private static TimeSpan? _defaultTtl; + private readonly IDatabase _blackList; + private readonly IEnumerable _servers; + + private RedisBlackList(IDatabase blackList, IEnumerable servers) { - private IDatabase _blackList; - private IEnumerable servers; - private static TimeSpan? _defaultTtl; + this._blackList = blackList; + this._servers = servers; + } - private RedisBlackList(IDatabase blackList, IEnumerable servers) + public async Task Delete(string key) + { + return await this._blackList.KeyDeleteAsync(key); + } + + public async Task DeleteAll() + { + foreach (var key in this._servers.SelectMany(x => x.Keys())) { - this._blackList = blackList; - this.servers = servers; + await this._blackList.KeyDeleteAsync(key); } + } - public static async Task CreateStoreAsync(string connectionString, TimeSpan? defaultTtl = null) - { - _defaultTtl = defaultTtl; - var options = ConfigurationOptions.Parse(connectionString); - options.AllowAdmin = true; - var redis = await ConnectionMultiplexer.ConnectAsync(options); - var blacklist = redis.GetDatabase(); - var servers = redis.GetEndPoints().Select(x => redis.GetServer(x)); + public async Task IsRevoked(string key) + { + var value = await this._blackList.StringGetAsync(key); - return new RedisBlackList(blacklist, servers); - } + return !value.HasValue; + } - public async Task Delete(string key) - { - return await _blackList.KeyDeleteAsync(key); - } + public async Task Revoke(string key) + { + var value = await this._blackList.StringSetAndGetAsync(key, key, _defaultTtl ?? TimeSpan.MaxValue); - public async Task DeleteAll() - { - foreach (var key in servers.SelectMany(x => x.Keys())) - { - await _blackList.KeyDeleteAsync(key); - } - } + return value.HasValue; + } - public async Task IsRevoked(string key) - { - var value = await _blackList.StringGetAsync(key); - return !value.HasValue; - } + public async Task Revoke(string key, TimeSpan expireAfter) + { + var value = await this._blackList.StringSetAndGetAsync(key, key, expireAfter); - public async Task Revoke(string key) - { - var value = await _blackList.StringSetAndGetAsync(key, key, _defaultTtl ?? TimeSpan.MaxValue); - return value.HasValue; - } + return value.HasValue; + } - public async Task Revoke(string key, TimeSpan expireAfter) - { - var value = await _blackList.StringSetAndGetAsync(key, key, expireAfter); - return value.HasValue; - } + public async Task Revoke(string key, DateTime expireOn) + { + var value = await this._blackList.StringSetAndGetAsync(key, key, expireOn - DateTimeOffset.Now); - public async Task Revoke(string key, DateTime expireOn) - { - var value = await _blackList.StringSetAndGetAsync(key, key, expireOn - DateTimeOffset.Now); - return value.HasValue; - } + return value.HasValue; + } + + public static async Task CreateStoreAsync(string connectionString, TimeSpan? defaultTtl = null) + { + _defaultTtl = defaultTtl; + var options = ConfigurationOptions.Parse(connectionString); + options.AllowAdmin = true; + var redis = await ConnectionMultiplexer.ConnectAsync(options); + var blacklist = redis.GetDatabase(); + var servers = redis.GetEndPoints() + .Select(x => redis.GetServer(x)); + + return new RedisBlackList(blacklist, servers); } } \ No newline at end of file diff --git a/Revoke.NET.Redis/Revoke.NET.Redis.csproj b/Revoke.NET.Redis/Revoke.NET.Redis.csproj index aca0ca2..a8d5fa5 100644 --- a/Revoke.NET.Redis/Revoke.NET.Redis.csproj +++ b/Revoke.NET.Redis/Revoke.NET.Redis.csproj @@ -1,42 +1,42 @@ - - netstandard2.0 - 10.0 - revoke.net.png - readme.md - LICENSE - Library - 2.0.0 - - Chakhoum Ahmed (github.com/rainxh11) - Revoke.NET Redis Store Extension - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.Redis - github - true - revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;redis;stackexchange;store - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - True - + + netstandard2.0 + 10.0 + revoke.net.png + readme.md + LICENSE + Library + 2.0.0 + + Chakhoum Ahmed (github.com/rainxh11) + Revoke.NET Redis Store Extension + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET/tree/main/Revoke.NET.Redis + github + true + revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip;mongo;redis;stackexchange;store + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + True + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/Revoke.NET.Redis/RevokeService.cs b/Revoke.NET.Redis/RevokeService.cs index 4238429..7b04831 100644 --- a/Revoke.NET.Redis/RevokeService.cs +++ b/Revoke.NET.Redis/RevokeService.cs @@ -1,23 +1,22 @@ -using Microsoft.Extensions.DependencyInjection; +namespace Revoke.NET.Redis; -namespace Revoke.NET.Redis +using Microsoft.Extensions.DependencyInjection; + +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddRevokeRedisStore(this IServiceCollection services) { - public static IServiceCollection AddRevokeRedisStore(this IServiceCollection services) - { - return services - .AddSingleton(provider => RedisBlackList.CreateStoreAsync("127.0.0.1:6379") - .GetAwaiter() - .GetResult()); - } + return services.AddSingleton( + provider => RedisBlackList.CreateStoreAsync("127.0.0.1:6379") + .GetAwaiter() + .GetResult()); + } - public static IServiceCollection AddRevokeRedisStore(this IServiceCollection services, string connectionString) - { - return services - .AddSingleton(provider => RedisBlackList.CreateStoreAsync(connectionString) - .GetAwaiter() - .GetResult()); - } + public static IServiceCollection AddRevokeRedisStore(this IServiceCollection services, string connectionString) + { + return services.AddSingleton( + provider => RedisBlackList.CreateStoreAsync(connectionString) + .GetAwaiter() + .GetResult()); } } \ No newline at end of file diff --git a/Revoke.NET/IBlackList.cs b/Revoke.NET/IBlackList.cs index aad12cf..00a5320 100644 --- a/Revoke.NET/IBlackList.cs +++ b/Revoke.NET/IBlackList.cs @@ -1,17 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace Revoke.NET; + +using System; using System.Threading.Tasks; -namespace Revoke.NET +public interface IBlackList { - public interface IBlackList - { - Task Revoke(string key, TimeSpan expireAfter); - Task Revoke(string key, DateTime expireOn); - Task Revoke(string key); - Task Delete(string key); - Task DeleteAll(); - Task IsRevoked(string key); - } + Task Revoke(string key, TimeSpan expireAfter); + + Task Revoke(string key, DateTime expireOn); + + Task Revoke(string key); + + Task Delete(string key); + + Task DeleteAll(); + + Task IsRevoked(string key); } \ No newline at end of file diff --git a/Revoke.NET/MemoryBlackList.cs b/Revoke.NET/MemoryBlackList.cs index 52c3b21..e684d4b 100644 --- a/Revoke.NET/MemoryBlackList.cs +++ b/Revoke.NET/MemoryBlackList.cs @@ -1,163 +1,169 @@ -using System; +namespace Revoke.NET; + +using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; -namespace Revoke.NET +public class MemoryCacheBlackList : IBlackList { - public class MemoryCacheBlackList : IBlackList + private static CancellationTokenSource _resetCacheToken = new(); + private readonly TimeSpan? _defaultTtl; + private readonly IMemoryCache _memoryCache; + + public MemoryCacheBlackList(IMemoryCache memoryCache, TimeSpan? defaultTtl = null) { - private IMemoryCache _memoryCache; - private TimeSpan? _defaultTtl; - private static CancellationTokenSource _resetCacheToken = new CancellationTokenSource(); + this._defaultTtl = defaultTtl; + this._memoryCache = memoryCache; + } - public MemoryCacheBlackList(IMemoryCache memoryCache, TimeSpan? defaultTtl = null) + public Task Revoke(string key) + { + var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(this._defaultTtl ?? TimeSpan.MaxValue); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); + try { - _defaultTtl = defaultTtl; - _memoryCache = memoryCache; - } + this._memoryCache.Set(key, key, options); - public Task Revoke(string key) - { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) - .SetAbsoluteExpiration(_defaultTtl ?? TimeSpan.MaxValue); - options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); - try - { - _memoryCache.Set(key, key, options); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } + return Task.FromResult(true); } - - public Task Delete(string key) + catch { - try - { - _memoryCache.Remove(key); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } + return Task.FromResult(false); } + } - public Task DeleteAll() + public Task Delete(string key) + { + try { - if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && - _resetCacheToken.Token.CanBeCanceled) - { - _resetCacheToken.Cancel(); - _resetCacheToken.Dispose(); - } - - _resetCacheToken = new CancellationTokenSource(); - return Task.CompletedTask; - } - + this._memoryCache.Remove(key); - public Task IsRevoked(string key) - { - return Task.FromResult(_memoryCache.TryGetValue(key, out _)); + return Task.FromResult(true); } - - public Task Revoke(string key, TimeSpan expireAfter) + catch { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) - .SetAbsoluteExpiration(expireAfter); - options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); - try - { - _memoryCache.Set(key, key, options); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } + return Task.FromResult(false); } + } - public Task Revoke(string key, DateTime expireOn) + public Task DeleteAll() + { + if (_resetCacheToken != null && !_resetCacheToken.IsCancellationRequested && _resetCacheToken.Token.CanBeCanceled) { - var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) - .SetAbsoluteExpiration(expireOn); - options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); - - try - { - _memoryCache.Set(key, key, options); - return Task.FromResult(true); - } - catch - { - return Task.FromResult(false); - } + _resetCacheToken.Cancel(); + _resetCacheToken.Dispose(); } - } + _resetCacheToken = new CancellationTokenSource(); + + return Task.CompletedTask; + } - public class MemoryBlackList : IBlackList + public Task IsRevoked(string key) { - private ConcurrentDictionary _blackList; - private readonly TimeSpan? defaultTtl; + return Task.FromResult(this._memoryCache.TryGetValue(key, out _)); + } - private MemoryBlackList(TimeSpan? defaultTtl) + public Task Revoke(string key, TimeSpan expireAfter) + { + var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(expireAfter); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); + try { - this.defaultTtl = defaultTtl; - _blackList = new ConcurrentDictionary(); - } + this._memoryCache.Set(key, key, options); - public static MemoryBlackList CreateStore(TimeSpan? defaultExpirationDuration = null) + return Task.FromResult(true); + } + catch { - return new MemoryBlackList(defaultExpirationDuration); + return Task.FromResult(false); } + } + + public Task Revoke(string key, DateTime expireOn) + { + var options = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.Normal) + .SetAbsoluteExpiration(expireOn); + options.AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token)); - public Task Delete(string key) + try { - return Task.FromResult(_blackList.TryRemove(key, out _)); - } + this._memoryCache.Set(key, key, options); - public Task Revoke(string key, TimeSpan expireAfter) + return Task.FromResult(true); + } + catch { - return Task.FromResult(_blackList.TryAdd(key, DateTime.Now.Add(expireAfter))); + return Task.FromResult(false); } + } +} + +public class MemoryBlackList : IBlackList +{ + private readonly TimeSpan? defaultTtl; + private readonly ConcurrentDictionary _blackList; + + private MemoryBlackList(TimeSpan? defaultTtl) + { + this.defaultTtl = defaultTtl; + this._blackList = new ConcurrentDictionary(); + } - public Task Revoke(string key, DateTime expireOn) + public Task Delete(string key) + { + return Task.FromResult(this._blackList.TryRemove(key, out _)); + } + + public Task Revoke(string key, TimeSpan expireAfter) + { + return Task.FromResult(this._blackList.TryAdd(key, DateTime.Now.Add(expireAfter))); + } + + public Task Revoke(string key, DateTime expireOn) + { + if (expireOn < DateTimeOffset.Now) { - if (expireOn < DateTimeOffset.Now) return Task.FromResult(false); - return Task.FromResult(_blackList.TryAdd(key, expireOn)); + return Task.FromResult(false); } - public Task DeleteAll() + return Task.FromResult(this._blackList.TryAdd(key, expireOn)); + } + + public Task DeleteAll() + { + this._blackList.Clear(); + + return Task.CompletedTask; + } + + public Task IsRevoked(string key) + { + if (this._blackList.TryGetValue(key, out var item)) { - _blackList.Clear(); - return Task.CompletedTask; + return Task.FromResult(item >= DateTime.Now); } - public Task IsRevoked(string key) - { - if (_blackList.TryGetValue(key, out var item)) - { - return Task.FromResult(item >= DateTime.Now); - } + return Task.FromResult(false); + } + public Task Revoke(string key) + { + if (DateTime.Now.Add(this.defaultTtl ?? TimeSpan.MaxValue) < DateTime.Now) + { return Task.FromResult(false); } - public Task Revoke(string key) - { - if (DateTime.Now.Add(defaultTtl ?? TimeSpan.MaxValue) < DateTime.Now) - return Task.FromResult(false); - return Task.FromResult(_blackList.TryAdd(key, DateTime.Now.Add(defaultTtl ?? TimeSpan.MaxValue))); - } + return Task.FromResult(this._blackList.TryAdd(key, DateTime.Now.Add(this.defaultTtl ?? TimeSpan.MaxValue))); + } + + public static MemoryBlackList CreateStore(TimeSpan? defaultExpirationDuration = null) + { + return new MemoryBlackList(defaultExpirationDuration); } } \ No newline at end of file diff --git a/Revoke.NET/README.md b/Revoke.NET/README.md index fcf4338..58d74d1 100644 --- a/Revoke.NET/README.md +++ b/Revoke.NET/README.md @@ -1,19 +1,28 @@ # Revoke.NET + .NET Utility to revoke access based on some given criterias including but not limited to: + - Web Tokens like JWT Bearer token - HTTP Request Header Paramters, Query, URL, Host, IP, Cookies, Body, FormData, Claims...etc # Installation + **First**, install the [`Revoke.NET`](https://www.nuget.org/packages/Revoke.NET) into your app + ```powershell Install-Package Revoke.NET ``` -or with dotnet cli: + +or with dotnet cli: + ```powershell dotnet add package Revoke.NET ``` + # How to use + simple create a new BlackList Store of type `IBlackListStore` + ```csharp using Revoke.NET; @@ -32,14 +41,19 @@ await store.Delete(key); // Delete a key from blacklist ``` # Usage with ASP.NET Core + Install the [`Revoke.NET.AspNetCore`](https://www.nuget.org/packages/Revoke.NET.AspNetCore) into your app + ```powershell Install-Package Revoke.NET.AspNetCore ``` -or with dotnet cli: + +or with dotnet cli: + ```powershell dotnet add package Revoke.NET.AspNetCore ``` + ```csharp using Revoke.NET; @@ -54,6 +68,7 @@ builder.Services ``` ### JWT Bearer Token Example + ```csharp using System.Net.Http.Headers; using Microsoft.AspNetCore.Mvc; diff --git a/Revoke.NET/Revoke.NET.csproj b/Revoke.NET/Revoke.NET.csproj index 9427edb..4ce8967 100644 --- a/Revoke.NET/Revoke.NET.csproj +++ b/Revoke.NET/Revoke.NET.csproj @@ -1,38 +1,38 @@  - - netstandard2.0;netstandard2.1;net6.0 - 10.0 - revoke.net.png - readme.md - LICENSE - Library - 2.0.1 - - Chakhoum Ahmed (github.com/rainxh11) - .NET Utility to blacklist and revoke access to stuff - © 2022 Chakhoum Ahmed - LICENSE - https://github.com/rainxh11/Revoke.NET - https://github.com/rainxh11/Revoke.NET - github - true - revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip - $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage - True - - - - - - - - - - - - - - - + + netstandard2.0;netstandard2.1;net6.0 + 10.0 + revoke.net.png + readme.md + LICENSE + Library + 2.0.1 + + Chakhoum Ahmed (github.com/rainxh11) + .NET Utility to blacklist and revoke access to stuff + © 2022 Chakhoum Ahmed + LICENSE + https://github.com/rainxh11/Revoke.NET + https://github.com/rainxh11/Revoke.NET + github + true + revoke;jwt;token;permission;deny;blacklist;aspnet;logout;expiration;invalidate;ip + $(TargetsForTfmSpecificBuildOutput);CopyProjectReferencesToPackage + True + + + + + + + + + + + + + + + diff --git a/Revoke.NET/RevokeService.cs b/Revoke.NET/RevokeService.cs index 4dcedff..3c6248f 100644 --- a/Revoke.NET/RevokeService.cs +++ b/Revoke.NET/RevokeService.cs @@ -1,65 +1,55 @@ -using System; -using System.Collections.Generic; -using System.Net.Http.Headers; -using System.Text; -using System.Threading.Tasks; +namespace Revoke.NET; + +using System; using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -namespace Revoke.NET +public static class RevokeService { - public static class RevokeService + public static IServiceCollection AddRevokeMemoryCacheStore(this IServiceCollection services, TimeSpan? defaultTtl = null) + { + services.TryAddSingleton(provider => new MemoryCacheBlackList(provider.GetService(), defaultTtl)); + + return services; + } + + /// + /// Register default InMemory BlackList Store Service + /// + /// + /// Default Blacklist Item Expiration Duration, null mean no expiration + /// + public static IServiceCollection AddRevokeInMemoryStore(this IServiceCollection services, TimeSpan? defaultTtl = null) { - public static IServiceCollection AddRevokeMemoryCacheStore(this IServiceCollection services, - TimeSpan? defaultTtl = null) - { - services.TryAddSingleton(provider => - new MemoryCacheBlackList(provider.GetService(), defaultTtl)); - return services; - } + services.TryAddSingleton(MemoryBlackList.CreateStore(defaultTtl)); - /// - /// Register default InMemory BlackList Store Service - /// - /// - /// Default Blacklist Item Expiration Duration, null mean no expiration - /// - public static IServiceCollection AddRevokeInMemoryStore(this IServiceCollection services, - TimeSpan? defaultTtl = null) - { - services - .TryAddSingleton(MemoryBlackList.CreateStore(defaultTtl)); - return services; - } + return services; + } - /// - /// Register BlackList Store Service - /// - /// - /// - /// - public static IServiceCollection AddRevokeStore(this IServiceCollection services, - Func configure) - { - services - .TryAddSingleton(configure()); - return services; - } + /// + /// Register BlackList Store Service + /// + /// + /// + /// + public static IServiceCollection AddRevokeStore(this IServiceCollection services, Func configure) + { + services.TryAddSingleton(configure()); + + return services; + } + + /// + /// Register BlackList Store Service + /// + /// + /// + /// + public static IServiceCollection AddRevokeStore(this IServiceCollection services, Func configure) + { + services.TryAddSingleton(configure); - /// - /// Register BlackList Store Service - /// - /// - /// - /// - public static IServiceCollection AddRevokeStore(this IServiceCollection services, - Func configure) - { - services - .TryAddSingleton(configure); - return services; - } + return services; } } \ No newline at end of file diff --git a/Test/Program.cs b/Test/Program.cs index 57ba8b7..5de0e00 100644 --- a/Test/Program.cs +++ b/Test/Program.cs @@ -1,5 +1,4 @@ -using Revoke.NET; -using Revoke.NET.Redis; +using Revoke.NET.Redis; var store = await RedisBlackList.CreateStoreAsync("localhost"); diff --git a/Test/Test.csproj b/Test/Test.csproj index 9adfe28..76df675 100644 --- a/Test/Test.csproj +++ b/Test/Test.csproj @@ -1,16 +1,16 @@  - - Exe - net6.0 - enable - enable - + + Exe + net6.0 + enable + enable + - - - - - + + + + +