Compare commits

..
25 Commits
Author SHA1 Message Date
saherelm b7a00244df last ... 2026-11-27 19:21:58 +03:30
saherelm bdc8791822 last ... 2026-11-26 19:36:49 +03:30
saherelm 4e114aa85a last ... 2026-11-21 00:08:36 +03:30
saherelm c2b2dd27c5 last ... 2026-11-20 20:39:18 +03:30
saherelm 002882300d last ... 2026-11-20 20:23:01 +03:30
saherelm bc5efed076 comment uncomplete authorization services ... 2026-11-20 14:11:48 +03:30
saherelm c8669bf493 last ... 2026-11-17 22:49:39 +03:30
saherelm ad69ce5ebc last ... 2026-11-17 18:11:45 +03:30
saherelm 19fece89bd last ... 2026-11-16 23:11:33 +03:30
saherelm cd9ee26c0f last ... 2026-11-16 11:20:25 +03:30
saherelm b6f20c9e79 last ... 2026-11-15 21:25:33 +03:30
saherelm f37ff01868 last ... 2026-11-15 17:53:32 +03:30
saherelm 825e554878 add Identity based Http Provider ... 2026-11-12 20:16:31 +03:30
saherelm 89bc95865a last ... 2026-11-06 19:11:50 +03:30
saherelm dc34e0f809 Implementing Policy Handler ... 2026-11-05 23:18:02 +03:30
saherelm 6888c73fb8 - اصلاح DI/XDIHelperExtension.cs برای هماهنگی ثبت وابستگی‌های جدید. 2026-11-04 17:51:29 +03:30
saherelm ac5517358e add support for person service ... 2026-10-31 21:40:44 +03:30
saherelm b99b182a1a Sort Ordering Usings ...
Using ApiKey Validations and Claims Parsing from Extensions ...
2026-10-30 00:20:01 +03:30
saherelm bac5d99c66 last ... 2026-10-28 14:26:52 +03:30
saherelm d43428e0b6 - Fix HttpContext RetrieveTokenAsXTokenResponse Extension Method;
- Add Extract Api Key Extension Method from HttpContext;
- Add Support for Token Introspect Validation in XIdentityService;
2026-10-23 19:52:31 +03:30
saherelm 72354dad4f complete xApiKeyUsage Middleware for Logging ApiKey Usages ... 2026-10-19 20:45:52 +03:30
saherelm 521f5e921f last ... 2026-10-19 17:59:10 +03:30
saherelm 05d9454c24 last ... 2026-10-18 05:46:34 +03:30
saherelm e9001a7735 last ... 2026-10-17 17:15:41 +03:30
saherelm d3dd9d4cd0 - Add XApiKeyAccess Authorization Attribute ...
- Refactor XApiAccountEndpoint and Add Application Routes into it ...
- Refactor IXIdentityProvider and XIdentityProvider and Add Support for Calling ApplicationController on xIds and Retrieve Responses of it ...
- Add XBaseTestIdentity Controller and Add Support for Test ApiKey Based Authorization on it ...
2026-10-17 01:21:14 +03:30
43 changed files with 4791 additions and 226 deletions
+151
View File
@@ -0,0 +1,151 @@
using System;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityModels.Models;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using xIdentityModels.Extensions;
using xIdentityService.Constants;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
namespace xIdentityService.Attributes
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = false,
Inherited = true
)]
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAsyncAuthorizationFilter
{
/// <summary>
/// Optional allowed scopes. If empty, no scope enforcement.
/// </summary>
public XApiKeyScope[] Scopes { get; set; }
public XApiKeyAccessAttribute(
XApiKeyScope[] scopes = null
)
{
//
if (!scopes.HasChild())
{
scopes = [XApiKeyScope.Read];
}
//
Scopes = scopes;
//
Policy = $"{XIdentityServiceConstants.PolicyCacheKeyPrefix}:{string.Join(";", Scopes)}";
}
/// <summary>
/// Authorization Filtering ...
/// </summary>
/// <param name="context"></param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//
// Access HttpContext ...
var http = context.HttpContext;
var cancellationToken = http.RequestAborted;
var error = XException.NotAuthorized.ToXError();
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
//
try
{
//
// Retrieve Identity Provider Service from DI ...
var identityService = http.RequestServices
.GetService<IXIdentityProvider>();
if (identityService.IsNull())
{
//
error.Message = "Api Key Service not Registered ...";
context.Result = new UnauthorizedObjectResult(error);
return;
}
//
// Checking Header ...
var apiKeyHeader = XHeader.ApiKey.GetStringValue();
if (!http.Request.Headers.ContainsKey(apiKeyHeader))
{
//
error.Message = "ApiKey not Exists ...";
context.Result = new UnauthorizedObjectResult(error);
return;
}
//
// Extract ApiKey from Header ...
var apiKey = http.Request.Headers[apiKeyHeader].ToString();
if (apiKey.IsNullOrEmpty())
{
//
error.Message = "ApiKey not Provided ...";
context.Result = new UnauthorizedObjectResult(error);
return;
}
//
// Extract Client IP ...
var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString();
var scopes =
!Scopes.HasChild()
? string.Empty
: Scopes.ToListString();
//
// Prepare Validation Request ...
var validationRequest = new XApiKeyValidationRequest
{
ApiKey = apiKey,
ClientIP = clientIP,
RequiredScope = scopes
};
//
// Validating ApiKey ...
var validationResponse = identityService.ValidateApiKey(
request: validationRequest,
cancellationToken: cancellationToken
)
.GetAwaiter()
.GetResult();
if (validationResponse.Errors.HasChild())
{
//
var message = validationResponse.Errors.ToListString(',');
error.Message = message;
context.Result = new UnauthorizedObjectResult(error);
return;
}
//
// Creating Claims ...
var claims = validationResponse.ToXClaims();
//
// Create Principal and Ticket ...
var identity = new ClaimsIdentity(claims, apiKeyAuthentication);
var principal = new ClaimsPrincipal(identity);
//
http.User = principal;
}
catch
{
//
error.Message = "ApiKey authorization failed ...";
context.Result = new UnauthorizedObjectResult(error);
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Authorization
{
public class XApiKeyRoleRequirement : IAuthorizationRequirement
{
public IReadOnlyCollection<string> Roles { get; }
public XApiKeyRoleRequirement(IEnumerable<string> roles)
{
Roles = [.. roles ?? []];
}
}
public class XApiKeyRoleHandler : AuthorizationHandler<XApiKeyRoleRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
XApiKeyRoleRequirement requirement
)
{
//
if (!requirement.Roles.Any())
{
context.Succeed(requirement);
return Task.CompletedTask;
}
//
if (requirement.Roles.Any(context.User.IsInRole))
{
context.Succeed(requirement);
}
//
return Task.CompletedTask;
}
}
}
+54
View File
@@ -0,0 +1,54 @@
using System;
using System.Linq;
using IdentityModel;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Authorization
{
public class XApiKeyScopeRequirement : IAuthorizationRequirement
{
public IReadOnlyCollection<string> Scopes { get; }
public XApiKeyScopeRequirement(IEnumerable<string> scopes)
{
Scopes = [.. scopes ?? []];
}
}
public class XApiKeyScopeHandler : AuthorizationHandler<XApiKeyScopeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
XApiKeyScopeRequirement requirement
)
{
//
if (!requirement.Scopes.Any())
{
//
context.Succeed(requirement);
return Task.CompletedTask;
}
//
var userScopes = new HashSet<string>(
context.User
.FindAll(JwtClaimTypes.Scope)
.SelectMany(c => c.Value.Split([' '], StringSplitOptions.RemoveEmptyEntries)),
StringComparer.OrdinalIgnoreCase
);
//
if (requirement.Scopes.All(s => userScopes.Contains(s)))
{
context.Succeed(requirement);
}
//
return Task.CompletedTask;
}
}
}
+1 -1
View File
@@ -221,7 +221,7 @@ namespace xIdentityService.Constants
[StringValue("Applications")] [StringValue("Applications")]
CreateApplication, CreateApplication,
[StringValue("Applications")] [StringValue("Applications/{id}")]
UpdateApplication, UpdateApplication,
[StringValue("Applications/{id}")] [StringValue("Applications/{id}")]
+7
View File
@@ -0,0 +1,7 @@
namespace xIdentityService.Constants
{
public struct XIdentityServiceConstants
{
public const string PolicyCacheKeyPrefix = "XAuth:Cache";
}
}
+65 -2
View File
@@ -1,3 +1,4 @@
using xModels.Dtos;
using xCommons.Constants; using xCommons.Constants;
using xCommons.Providers; using xCommons.Providers;
using xCommons.Extensions; using xCommons.Extensions;
@@ -10,6 +11,7 @@ using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants; using xIdentityModels.Constants;
using System.Collections.Generic; using System.Collections.Generic;
using xIdentityService.Constants; using xIdentityService.Constants;
using xIdentityModels.Extensions;
using xIdentityService.Interfaces; using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
@@ -82,7 +84,7 @@ namespace xIdentityService.Controllers
} }
// //
return result; return result;
} }
/// <summary> /// <summary>
@@ -106,7 +108,7 @@ namespace xIdentityService.Controllers
} }
// //
return result; return result;
} }
/// <summary> /// <summary>
@@ -268,6 +270,7 @@ namespace xIdentityService.Controllers
return null; return null;
} }
//
var xTokens = await RetrieveTokensAsXTokenResponse(); var xTokens = await RetrieveTokensAsXTokenResponse();
var result = new XUserClaimsInfoDto( var result = new XUserClaimsInfoDto(
xTokens.AccessToken, xTokens.AccessToken,
@@ -303,6 +306,66 @@ namespace xIdentityService.Controllers
// //
return result; return result;
} }
/// <summary>
/// Get Authenticated ApiKey Person ...
/// </summary>
/// <returns></returns>
[NonAction]
public XPersonDto GetApiKeyPerson()
{
//
var result = User.ExtractApiKeyUser();
return result;
}
/// <summary>
/// Validate and Get Authenticated ApiKey Person ...
/// </summary>
/// <returns></returns>
[NonAction]
public XPersonDto ValidateAndGetApiKeyPerson()
{
//
var result = User.ExtractApiKeyUser();
if (result.IsNullOrDefault())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
/// <summary>
/// Get Authenticated JWT Person ...
/// </summary>
/// <returns></returns>
[NonAction]
public XPersonDto GetAuthenticatedPerson()
{
//
var result = User.ExtractAuthenticatedUser();
return result;
}
/// <summary>
/// Validate and Get Authenticated JWT Person ...
/// </summary>
/// <returns></returns>
[NonAction]
public XPersonDto ValidateAndGetAuthenticatedPerson()
{
//
var result = User.ExtractAuthenticatedUser();
if (result.IsNullOrDefault())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
#endregion #endregion
} }
} }
+111
View File
@@ -0,0 +1,111 @@
using xCommons.Providers;
using xCommons.Attributes;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using xIdentityService.Interfaces;
using xIdentityService.Attributes;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Controllers
{
public abstract class XBaseTestIdentityController : XBaseIdentityController
{
protected XBaseTestIdentityController(
ILogger<XBaseTestIdentityController> logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{ }
//
#region ApiKey Actions ...
/// <summary>
/// a simple Hello for Accessing ApiKey Authorization ...
/// </summary>
/// <returns></returns>
[XApiKeyAccess]
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyAccess")]
public ActionResult<string> HiApiKeyAccess()
{
//
var result = $"Hi ApiKey Access, is Passed ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello for Accessing ApiKey Read Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyReadAccess")]
[XApiKeyAccess(Scopes = [XApiKeyScope.Read])]
public ActionResult<string> HiApiKeyReadAccess()
{
//
var result = $"Hi ApiKey Read Access, is Passed ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello for Accessing ApiKey Write Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyWriteAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Write])]
public ActionResult<string> HiApiKeyWriteAccess()
{
//
var result = $"Hi ApiKey Write Access, is Passed ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello for Accessing ApiKey Manage Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyManageAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Manage])]
public ActionResult<string> HiApiKManageAccess()
{
//
var result = $"Hi ApiKey Manage Access, is Passed ...";
//
return Ok(result);
}
/// <summary>
/// a simple Hello for Accessing ApiKey Admin Access ...
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyAdminAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Admin])]
public ActionResult<string> HiApiKeyAdminAccess()
{
//
var result = $"Hi ApiKey Admin Access, is Passed ...";
//
return Ok(result);
}
#endregion
}
}
+139 -51
View File
@@ -1,6 +1,8 @@
using System; using System;
using xCommons.Extensions; using xCommons.Extensions;
using xExceptions.Constants;
using xCommons.Authorization; using xCommons.Authorization;
using xHttpService.Interfaces;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using xIdentityService.Security; using xIdentityService.Security;
using xIdentityService.Constants; using xIdentityService.Constants;
@@ -13,17 +15,36 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection; using IdentityModel.AspNetCore.OAuth2Introspection;
namespace xIdentityService.DI { namespace xIdentityService.DI
public static partial class XDIHelperExtension { {
public static partial class XDIHelperExtension
{
/// <summary> /// <summary>
/// Extract Module Configuration Structure from IConfiguration interface /// Extract Module Configuration Structure from IConfiguration interface
/// </summary> /// </summary>
/// <param name="config"></param> /// <param name="config"></param>
/// <returns></returns> /// <returns></returns>
public static XIdentityServiceConfiguration GetXIdentityServiceConfiguration (this IConfiguration config) { public static XIdentityServiceConfiguration GetXIdentityServiceConfiguration(this IConfiguration config)
{
// //
var xIdentityServiceConfigSection = config.GetSection (ConfigurationNodeNames.IDENTITY_SERVICE_NODE_NAME); var xIdentityServiceConfigSection = config.GetSection(ConfigurationNodeNames.IDENTITY_SERVICE_NODE_NAME);
return xIdentityServiceConfigSection.Get<XIdentityServiceConfiguration> (); return xIdentityServiceConfigSection.Get<XIdentityServiceConfiguration>();
}
/// <summary>
/// Register Identity Based Support Http Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXIdentityHttpService(
this IServiceCollection source
)
{
//
var httpProvider = source.GetRegisteredService<IXHttpProvider>();
if (!httpProvider.IsNull())
{
source.AddScoped<IXIdentityHttpProvider, XIdentityHttpProvider>();
}
} }
/// <summary> /// <summary>
@@ -32,14 +53,15 @@ namespace xIdentityService.DI {
/// <param name="services"></param> /// <param name="services"></param>
/// <param name="configuration"></param> /// <param name="configuration"></param>
/// <param name="lifeTime"></param> /// <param name="lifeTime"></param>
public static void AddXIdentityService ( public static void AddXIdentityService(
this IServiceCollection services, this IServiceCollection services,
IConfiguration configuration, IConfiguration configuration,
ServiceLifetime lifeTime = ServiceLifetime.Singleton ServiceLifetime lifeTime = ServiceLifetime.Singleton
) { )
{
// //
var identityConfiguration = configuration.GetXIdentityServiceConfiguration (); var identityConfiguration = configuration.GetXIdentityServiceConfiguration();
AddIdentityService ( AddIdentityService(
services, services,
identityConfiguration, identityConfiguration,
lifeTime lifeTime
@@ -52,12 +74,13 @@ namespace xIdentityService.DI {
/// <param name="services"></param> /// <param name="services"></param>
/// <param name="configuration"></param> /// <param name="configuration"></param>
/// <param name="lifeTime"></param> /// <param name="lifeTime"></param>
public static void AddXIdentityService ( public static void AddXIdentityService(
this IServiceCollection services, this IServiceCollection services,
XIdentityServiceConfiguration configuration, XIdentityServiceConfiguration configuration,
ServiceLifetime lifeTime = ServiceLifetime.Singleton ServiceLifetime lifeTime = ServiceLifetime.Singleton
) { )
AddIdentityService (services, configuration, lifeTime); {
AddIdentityService(services, configuration, lifeTime);
} }
/// <summary> /// <summary>
@@ -66,60 +89,112 @@ namespace xIdentityService.DI {
/// <param name="services"></param> /// <param name="services"></param>
/// <param name="lifeTime"></param> /// <param name="lifeTime"></param>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public static void AddXTokenProvider<T> ( public static void AddXTokenProvider<T>(
this IServiceCollection services, this IServiceCollection services,
ServiceLifetime lifeTime = ServiceLifetime.Singleton) ServiceLifetime lifeTime = ServiceLifetime.Singleton
where T : IXTokenProvider { )
where T : IXTokenProvider
{
// //
Console.WriteLine ("IdentityService: Add Custom Token Provider ..."); Console.WriteLine("IdentityService: Add Custom Token Provider ...");
services.Add (new ServiceDescriptor (typeof (IXTokenProvider), typeof (T), lifeTime)); services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(T), lifeTime));
}
/// <summary>
/// Register Person Service ...
/// </summary>
/// <param name="source"></param>
/// <param name="lifeTime"></param>
public static void AddXPersonService(
this IServiceCollection source,
ServiceLifetime lifeTime = ServiceLifetime.Singleton
)
{
source.Add(new ServiceDescriptor(typeof(IXPersonService), typeof(XPersonService), lifeTime));
Console.WriteLine("IdentityService: Add PersonService ...");
}
/// <summary>
/// Register Policy Handler Service ...
/// </summary>
/// <param name="source"></param>
public static void AddXPolicyHandler(
this IServiceCollection source
)
{
source.AddSingleton<IXPolicyHandler, XPolicyHandler>();
}
public static void AddXRoleHierarchyResolver(
this IServiceCollection source
)
{
//
// Check Provider ...
var providerService = source.GetRegisteredService<IXRoleProvider>();
if (providerService.IsNull())
{
XException.InvalidConfiguration.Throw();
}
//
source.AddScoped<IXRoleHierarchyResolver, XRoleHierarchyResolver>();
} }
/// <summary> /// <summary>
/// Use Authentication /// Use Authentication
/// </summary> /// </summary>
/// <param name="app"></param> /// <param name="app"></param>
public static void UseXIdentityService (this IApplicationBuilder app) { public static void UseXIdentityService(this IApplicationBuilder app)
app.UseAuthentication (); {
app.UseAuthentication();
} }
// //
#region Private ... #region Private ...
private static void AddIdentityService ( private static void AddIdentityService(
this IServiceCollection services, this IServiceCollection services,
XIdentityServiceConfiguration config, XIdentityServiceConfiguration config,
ServiceLifetime lifeTime = ServiceLifetime.Singleton ServiceLifetime lifeTime = ServiceLifetime.Singleton
) { )
{
// //
services.AddSingleton<XIdentityServiceConfiguration> (config); services.AddSingleton<XIdentityServiceConfiguration>(config);
//
// Register Policy Handler ...
services.AddXPolicyHandler();
// //
var builder = services var builder = services
.AddAuthentication (XAuthenticationScheme.XToken.GetStringValue ()); .AddAuthentication(XAuthenticationScheme.XToken.GetStringValue());
// //
// Add JWT Handler ... // Add JWT Handler ...
builder.AddJwtBearer ( builder.AddJwtBearer(
XAuthenticationScheme.XToken.GetStringValue (), options => { XAuthenticationScheme.XToken.GetStringValue(), options =>
{
// //
options.Authority = config.Authority; options.Authority = config.Authority;
options.TokenValidationParameters.ValidateAudience = false; options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.ValidTypes = new [] { "at+jwt" }; options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
// //
options.ForwardDefaultSelector = context => { options.ForwardDefaultSelector = context =>
{
// //
var path = context.Request.Path.Value; var path = context.Request.Path.Value;
// //
var fromHeader = TokenRetrieval.FromAuthorizationHeader (); var fromHeader = TokenRetrieval.FromAuthorizationHeader();
var fromQuery = TokenRetrieval.FromQueryString (); var fromQuery = TokenRetrieval.FromQueryString();
var bearerToken = fromHeader (context.Request) ?? fromQuery (context.Request); var bearerToken = fromHeader(context.Request) ?? fromQuery(context.Request);
// //
var result = XAuthenticationScheme.XToken.GetStringValue (); var result = XAuthenticationScheme.XToken.GetStringValue();
if (!bearerToken.IsNull () && !bearerToken.Contains (".")) { if (!bearerToken.IsNull() && !bearerToken.Contains("."))
result = XAuthenticationScheme.XIntrospection.GetStringValue (); {
result = XAuthenticationScheme.XIntrospection.GetStringValue();
} }
// //
@@ -129,21 +204,23 @@ namespace xIdentityService.DI {
// //
// Add OAuthIntrospect ... // Add OAuthIntrospect ...
builder.AddOAuth2Introspection ( builder.AddOAuth2Introspection(
XAuthenticationScheme.XIntrospection.GetStringValue (), options => { XAuthenticationScheme.XIntrospection.GetStringValue(), options =>
{
// //
options.Authority = config.Authority; options.Authority = config.Authority;
options.ClientId = config.ApiName; options.ClientId = config.ApiName;
options.ClientSecret = config.ClientSecret; options.ClientSecret = config.ClientSecret;
// //
options.TokenRetriever = new Func<HttpRequest, string> (req => { options.TokenRetriever = new Func<HttpRequest, string>(req =>
{
// //
var fromHeader = TokenRetrieval.FromAuthorizationHeader (); var fromHeader = TokenRetrieval.FromAuthorizationHeader();
var fromQuery = TokenRetrieval.FromQueryString (); var fromQuery = TokenRetrieval.FromQueryString();
// //
var bearerToken = fromHeader (req) ?? fromQuery (req); var bearerToken = fromHeader(req) ?? fromQuery(req);
// //
return bearerToken; return bearerToken;
@@ -152,30 +229,41 @@ namespace xIdentityService.DI {
// //
// Register Authorization Handler ... // Register Authorization Handler ...
services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler> (); services.AddSingleton<IAuthorizationHandler, RequiredRolesHandler>();
Console.WriteLine ("IdentityService: register Authorization Handlers ..."); Console.WriteLine("IdentityService: register Authorization Handlers ...");
// //
// Register Identity Provider ... // Register Identity Provider ...
services.Add (new ServiceDescriptor (typeof (IXIdentityProvider), typeof (XIdentityProvider), lifeTime)); services.Add(new ServiceDescriptor(typeof(IXIdentityProvider), typeof(XIdentityProvider), lifeTime));
Console.WriteLine ("IdentityService: Register IdentityProvider ..."); Console.WriteLine("IdentityService: Register IdentityProvider ...");
//
// Register Person Service ...
services.AddXPersonService(lifeTime);
//
// Register Identity Based Http Provider ...
services.AddXIdentityHttpService();
// //
// Try To Register InMemoryTokenProvier if it's not Provided ... // Try To Register InMemoryTokenProvier if it's not Provided ...
IXTokenProvider xTokenProvider = null; IXTokenProvider xTokenProvider = null;
try { try
xTokenProvider = services.GetRegisteredService<IXTokenProvider> (); {
} catch { } xTokenProvider = services.GetRegisteredService<IXTokenProvider>();
if (xTokenProvider.IsNull ()) { }
catch { }
if (xTokenProvider.IsNull())
{
// //
Console.WriteLine ("IdentityService: there is no Custom Token Provider, Adding InMemoryTokenProvider instead ..."); Console.WriteLine("IdentityService: there is no Custom Token Provider, Adding InMemoryTokenProvider instead ...");
services.Add (new ServiceDescriptor (typeof (IXTokenProvider), typeof (XInMemoryTokenProvider), lifeTime)); services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(XInMemoryTokenProvider), lifeTime));
} }
// //
// Adding Security Provider ... // Adding Security Provider ...
services.Add (new ServiceDescriptor (typeof (IXSecurityProvider), typeof (XSecurityProvider), lifeTime)); services.Add(new ServiceDescriptor(typeof(IXSecurityProvider), typeof(XSecurityProvider), lifeTime));
Console.WriteLine ("IdentityService: Register Security Provider ..."); Console.WriteLine("IdentityService: Register Security Provider ...");
} }
#endregion #endregion
} }
+80 -36
View File
@@ -7,17 +7,20 @@ using xIdentityService.Constants;
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
namespace xIdentityService.Extensions { namespace xIdentityService.Extensions
public static class HttpContextExtensions { {
public static class HttpContextExtensions
{
/// <summary> /// <summary>
/// Retrieve Authentication Service ... /// Retrieve Authentication Service ...
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <returns></returns> /// <returns></returns>
public static IAuthenticationService GetAuthenticationService (this HttpContext context) { public static IAuthenticationService GetAuthenticationService(this HttpContext context)
{
// //
var result = context.RequestServices var result = context.RequestServices
.GetRequiredService<IAuthenticationService> (); .GetRequiredService<IAuthenticationService>();
// //
return result; return result;
@@ -30,34 +33,37 @@ namespace xIdentityService.Extensions {
/// <param name="tokenName"></param> /// <param name="tokenName"></param>
/// <param name="scheme"></param> /// <param name="scheme"></param>
/// <returns></returns> /// <returns></returns>
public static async Task<string> GetXTokenAsync ( public static async Task<string> GetXTokenAsync(
this HttpContext context, this HttpContext context,
string tokenName, string tokenName,
XAuthenticationScheme scheme = XAuthenticationScheme.XToken XAuthenticationScheme scheme = XAuthenticationScheme.XToken
) { )
{
// //
// Validate Args ... // Validate Args ...
if (tokenName.IsNullOrEmpty ()) { if (tokenName.IsNullOrEmpty())
{
return null; return null;
} }
// //
var authService = context.GetAuthenticationService (); var authService = context.GetAuthenticationService();
if (authService.IsNull ()) { if (authService.IsNull())
{
return null; return null;
} }
// //
var authResult = await authService var authResult = await authService
.AuthenticateAsync ( .AuthenticateAsync(
context, context,
scheme scheme
.GetStringValue () .GetStringValue()
); );
// //
var result = authResult?.Properties? var result = authResult?.Properties?
.GetTokenValue (tokenName); .GetTokenValue(tokenName);
return result; return result;
} }
@@ -65,22 +71,25 @@ namespace xIdentityService.Extensions {
/// Retrieve Access Token /// Retrieve Access Token
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static async Task<string> GetAccessToken (this HttpContext context) { public static async Task<string> GetAccessToken(this HttpContext context)
{
// //
var accessToken = context.Request.Headers[XAuthorization.Header] var accessToken = context.Request.Headers[XAuthorization.Header]
.ToString (); .ToString();
if (accessToken.IsNullOrEmpty ()) { if (accessToken.IsNullOrEmpty())
{
accessToken = await context accessToken = await context
.GetTokenAsync (XAuthorization.AccessToken); .GetTokenAsync(XAuthorization.AccessToken);
} }
// //
if (accessToken if (accessToken
.ToNormalString () .ToNormalString()
.Contains (XAuthorization.TokenIdentifier .Contains(XAuthorization.TokenIdentifier
.ToNormalString ())) { .ToNormalString()))
{
accessToken = accessToken accessToken = accessToken
.Remove (0, XAuthorization.TokenIdentifier.Length); .Remove(0, XAuthorization.TokenIdentifier.Length);
} }
// //
@@ -91,13 +100,15 @@ namespace xIdentityService.Extensions {
/// Retrieve Refresh Token /// Retrieve Refresh Token
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static async Task<string> GetRefreshToken (this HttpContext context) { public static async Task<string> GetRefreshToken(this HttpContext context)
{
// //
var refreshToken = context.Request.Headers[XAuthorization.RefreshToken] var refreshToken = context.Request.Headers[XAuthorization.RefreshToken]
.ToString (); .ToString();
if (refreshToken.IsNullOrEmpty ()) { if (refreshToken.IsNullOrEmpty())
{
refreshToken = await context refreshToken = await context
.GetTokenAsync (XAuthorization.RefreshToken); .GetTokenAsync(XAuthorization.RefreshToken);
} }
// //
@@ -108,17 +119,19 @@ namespace xIdentityService.Extensions {
/// Retrieve Access Token Expiration Date /// Retrieve Access Token Expiration Date
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static async Task<long> GetTokenExpiresAt (this HttpContext context) { public static async Task<long> GetTokenExpiresAt(this HttpContext context)
{
// //
var expiresAtStr = context.Request.Headers[XAuthorization.ExpiresAt] var expiresAtStr = context.Request.Headers[XAuthorization.ExpiresAt]
.ToString (); .ToString();
if (expiresAtStr.IsNullOrEmpty ()) { if (expiresAtStr.IsNullOrEmpty())
{
expiresAtStr = await context expiresAtStr = await context
.GetTokenAsync (XAuthorization.ExpiresAt); .GetTokenAsync(XAuthorization.ExpiresAt);
} }
// //
var expiresAt = expiresAtStr.ConvertTo<long> (); var expiresAt = expiresAtStr.ConvertTo<long>();
// //
return expiresAt; return expiresAt;
@@ -128,18 +141,49 @@ namespace xIdentityService.Extensions {
/// Retrieve All Required Tokens /// Retrieve All Required Tokens
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static async Task<XTokenResponse> RetrieveTokensAsXTokenResponse (HttpContext context) { public static async Task<XTokenResponse> RetrieveTokensAsXTokenResponse(this HttpContext context)
{
// //
var accessToken = await GetAccessToken (context); var accessToken = await GetAccessToken(context);
var refreshToken = await GetRefreshToken (context); var refreshToken = await GetRefreshToken(context);
var expiresAt = await GetTokenExpiresAt (context); var expiresAt = await GetTokenExpiresAt(context);
// //
return new XTokenResponse { return new XTokenResponse
{
AccessToken = accessToken, AccessToken = accessToken,
RefreshToken = refreshToken, RefreshToken = refreshToken,
ExpiresAt = expiresAt ExpiresAt = expiresAt
}; };
} }
/// <summary>
/// Retrieve Request Path ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string GetRequestPath(this HttpContext source)
{
//
var result = source.Request.GetRequestPath();
return result;
}
/// <summary>
/// Retrieve Request Path ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string GetRequestPath(this HttpRequest source)
{
//
var path = source.Path;
var pathBase = source.PathBase;
var query = source.QueryString;
//
var result = $"{pathBase}{path}{query}";
return result;
}
} }
} }
+20
View File
@@ -0,0 +1,20 @@
using xIdentityService.Models;
using xIdentityService.Interfaces;
using Microsoft.Extensions.DependencyInjection;
namespace xIdentityService.Extensions
{
public static class XAuthorizationExtensions
{
/// <summary>
/// Add Authorization Cache ...
/// </summary>
/// <param name="source"></param>
public static void AddXAuthorizationCache(
this IServiceCollection source
)
{
source.AddSingleton<IXAuthorizationCache, XAuthorizationCache>();
}
}
}
+270
View File
@@ -1,15 +1,30 @@
using System.Linq;
using xModels.Dtos; using xModels.Dtos;
using xCommons.Extensions;
using xIdentityModels.Dtos; using xIdentityModels.Dtos;
using xIdentityService.Models;
using xIdentityModels.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using xCommons.Authorization;
using IdentityModel;
using xCommons.Constants;
namespace xIdentityService.Extensions namespace xIdentityService.Extensions
{ {
public static class XModelExtensions public static class XModelExtensions
{ {
/// <summary>
/// Converts OpenActionUserInfoDto to XPersonDto ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static XPersonDto ToXPersonDto(this XOpenActionUserInfoDto source) public static XPersonDto ToXPersonDto(this XOpenActionUserInfoDto source)
{ {
// //
var result = new XPersonDto var result = new XPersonDto
{ {
UserId = source.UserId,
Avatar = source.Avatar, Avatar = source.Avatar,
Lastname = source.Lastname, Lastname = source.Lastname,
Username = source.Username, Username = source.Username,
@@ -19,5 +34,260 @@ namespace xIdentityService.Extensions
// //
return result; return result;
} }
/// <summary>
/// Check an Authorization which Can Applyed or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool HasRequirements(
this XEffectiveAuthorizationDto source
)
{
//
var result =
!source.IsNullOrDefault() &&
!source.PolicyName.IsNullOrEmpty() &&
source.RequireEnabledUser ||
source.RequireAuthenticatedUser ||
source.EffectiveRoles.HasChild() ||
source.EffectiveScopes.HasChild() ||
source.EffectiveClaims.HasChild();
//
return result;
}
/// <summary>
/// Extract Effective Authorization ...
/// </summary>
/// <param name="source"></param>
/// <param name="effectiveRoles"></param>
/// <returns></returns>
public static XEffectiveAuthorizationDto ToEffectiveAuthorization(
this XPolicyDefinition source,
IEnumerable<string> effectiveRoles
)
{
//
XEffectiveAuthorizationDto result = null;
if (source.IsNull() ||
source.Name.IsNullOrEmpty())
{
return result;
}
//
result = new XEffectiveAuthorizationDto
{
//
PolicyName = source.Name,
EffectiveRoles = [.. effectiveRoles],
RequireEnabledUser = source.RequireEnabledUser,
RequireAuthenticatedUser = source.RequireAuthenticatedUser,
EffectiveScopes = source.RequiredScopes
.ParseListString<string>()?
.ToHashSet() ?? [],
EffectiveClaims = source.RequiredClaims.ToRequiredClaims()
};
//
return result;
}
/// <summary>
/// Extract Effective Authorization ...
/// </summary>
/// <param name="source"></param>
/// <param name="effectiveRoles"></param>
/// <returns></returns>
public static XEffectiveAuthorizationDto ToEffectiveAuthorization(
this XPolicyDefinitionDto source,
IEnumerable<string> effectiveRoles
)
{
//
XEffectiveAuthorizationDto result = null;
if (source.IsNull() ||
source.Name.IsNullOrEmpty())
{
return result;
}
//
var scopes = source.RequiredScopes.ParseListString<string>();
result = new XEffectiveAuthorizationDto
{
PolicyName = source.Name,
EffectiveScopes = scopes.HasChild()
? [.. scopes]
: [],
EffectiveRoles = effectiveRoles.HasChild()
? [.. effectiveRoles]
: [],
RequireEnabledUser = source.RequireEnabledUser,
EffectiveClaims = source.RequiredClaims.ToRequiredClaims(),
RequireAuthenticatedUser = source.RequireAuthenticatedUser
};
//
return result;
}
/// <summary>
/// Merge to Effective Authorization Samples ...
/// </summary>
/// <param name="source"></param>
/// <param name="other"></param>
/// <returns></returns>
public static XEffectiveAuthorizationDto MergeWith(
this XEffectiveAuthorizationDto source,
XEffectiveAuthorizationDto other
)
{
//
if (source.IsNull()) return other;
if (other.IsNull()) return source;
//
// Roles
var mergedRoles = new HashSet<string>(source.EffectiveRoles);
mergedRoles.UnionWith(other.EffectiveRoles);
//
// Scopes
var mergedScopes = new HashSet<string>(source.EffectiveScopes);
mergedScopes.UnionWith(other.EffectiveScopes);
//
// Claims
var mergedClaims = new List<XRequiredClaimDto>(source.EffectiveClaims);
mergedClaims.AddRange(other.EffectiveClaims);
//
var result = new XEffectiveAuthorizationDto
{
//
EffectiveRoles = mergedRoles,
EffectiveScopes = mergedScopes,
EffectiveClaims = mergedClaims,
PolicyName = source.PolicyName ?? other.PolicyName,
RequireEnabledUser =
source.RequireEnabledUser || other.RequireEnabledUser,
RequireAuthenticatedUser =
source.RequireAuthenticatedUser || other.RequireAuthenticatedUser,
};
//
return result;
}
/// <summary>
/// Make Authorization Policy Based on Dynamically loaded Descriptions ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static AuthorizationPolicy ToAuthorizationPolicy(
this XEffectiveAuthorizationDto source
)
{
//
AuthorizationPolicy result = null;
if (source.IsNull() ||
source.PolicyName.IsNullOrEmpty())
{
return result;
}
//
var builder = new AuthorizationPolicyBuilder();
//
// Check and Handle Authenticated User ...
if (source.RequireAuthenticatedUser)
{
builder.RequireAuthenticatedUser();
}
//
// Check and Apply Effective Roles ...
if (source.EffectiveRoles.HasChild())
{
//
builder
.AddRequirements(new RequiredRolesRequirement([.. source.EffectiveRoles]));
}
//
// Check and Apply Effective Scopes ...
if (source.EffectiveScopes.HasChild())
{
//
builder.RequireClaim(
JwtClaimTypes.Scope,
[.. source.EffectiveScopes]);
}
//
// Check and Apply Effective Claims ...
foreach (var claim in source.EffectiveClaims)
{
//
// Validate Type ...
if (claim.Type.IsNullOrEmpty())
{
continue;
}
//
if (claim.Values.HasChild())
{
//
builder
.RequireClaim(
claim.Type,
[.. claim.Values]);
}
else
{
builder.RequireClaim(claim.Type);
}
}
//
// Check, Apply and Handle
// IsBanned and IsEnabled Claims ...
if (source.RequireEnabledUser &&
source.RequireAuthenticatedUser)
{
//
builder.RequireClaim(
XCustomClaims.IsBanned,
false.ToString(),
false.ToString()
.ToNormalString());
//
builder.RequireClaim(
XCustomClaims.IsEnabled,
true.ToString(),
true.ToString()
.ToNormalString());
}
//
// Last Validation ...
if (!builder.Requirements.HasChild())
{
builder.RequireAuthenticatedUser();
}
//
// Build and Create Result ...
result = builder.Build();
//
return result;
}
} }
} }
+238
View File
@@ -0,0 +1,238 @@
using System.Linq;
using IdentityModel;
using xCommons.Constants;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xIdentityModels.Models;
using xCommons.Authorization;
using xIdentityService.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Extensions
{
public static class XPolicyDefinitionExtensions
{
/// <summary>
/// Deserialize Json Array of Required Claims ...
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
public static List<XRequiredClaimDto> ToRequiredClaims(this string json)
{
//
var result = new List<XRequiredClaimDto>();
//
// Validate ...
if (json.IsNullOrEmpty())
{
return result;
}
//
try
{
//
result = json.FromJSON<List<XRequiredClaimDto>>();
}
catch
{ }
//
if (result.IsNull())
{
result = [];
}
//
return result;
}
/// <summary>
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
/// </summary>
/// <param name="source"></param>
/// <param name="effectiveRoles">already resolved by IXRoleHierarchyResolver</param>
/// <returns></returns>
public static AuthorizationPolicy ToAuthorizationPolicy(
this XPolicyDefinition source,
IEnumerable<string> effectiveRoles
)
{
//
if (source.IsNull() || source.Name.IsNullOrEmpty())
{
return null;
}
//
var builder = new AuthorizationPolicyBuilder();
//
// Authenticated User ...
if (source.RequireAuthenticatedUser)
{
builder.RequireAuthenticatedUser();
}
//
// Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ...
if (effectiveRoles.HasChild())
{
builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray()));
}
//
// Scopes ...
var scopes = source.RequiredScopes.ParseListString<string>();
if (scopes.HasChild())
{
builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]);
}
//
// Custom Claims ...
foreach (var claim in source.RequiredClaims.ToRequiredClaims())
{
//
if (claim.Type.IsNullOrEmpty())
{
continue;
}
//
if (claim.Values.HasChild())
{
builder.RequireClaim(claim.Type, claim.Values.ToArray());
}
else
{
builder.RequireClaim(claim.Type);
}
}
//
// Enabled User (IsBanned=false & IsEnabled=true) ...
if (source.RequireEnabledUser)
{
//
builder.RequireClaim(
XCustomClaims.IsBanned,
false.ToString(),
false.ToString().ToNormalString()
);
//
builder.RequireClaim(
XCustomClaims.IsEnabled,
true.ToString(),
true.ToString().ToNormalString()
);
}
//
// Nothing Required => at least Deny Anonymous to avoid an Empty Policy ...
if (!builder.Requirements.HasChild())
{
builder.RequireAuthenticatedUser();
}
//
return builder.Build();
}
/// <summary>
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
/// </summary>
/// <param name="source"></param>
/// <param name="effectiveRoles">already resolved by IXRoleHierarchyResolver</param>
/// <returns></returns>
public static AuthorizationPolicy ToAuthorizationPolicy(
this XPolicyDefinitionDto source,
IEnumerable<string> effectiveRoles
)
{
//
if (source.IsNull() || source.Name.IsNullOrEmpty())
{
return null;
}
//
var builder = new AuthorizationPolicyBuilder();
//
// Authenticated User ...
if (source.RequireAuthenticatedUser)
{
builder.RequireAuthenticatedUser();
}
//
// Roles (RequiredRolesRequirement, handled by RequiredRolesHandler) ...
if (effectiveRoles.HasChild())
{
builder.AddRequirements(new RequiredRolesRequirement(effectiveRoles.ToArray()));
}
//
// Scopes ...
var scopes = source.RequiredScopes.ParseListString<string>();
if (scopes.HasChild())
{
builder.RequireClaim(JwtClaimTypes.Scope, [.. scopes]);
}
//
// Custom Claims ...
foreach (var claim in source.RequiredClaims.ToRequiredClaims())
{
//
if (claim.Type.IsNullOrEmpty())
{
continue;
}
//
if (claim.Values.HasChild())
{
builder.RequireClaim(claim.Type, claim.Values.ToArray());
}
else
{
builder.RequireClaim(claim.Type);
}
}
//
// Enabled User (IsBanned=false & IsEnabled=true) ...
if (source.RequireEnabledUser)
{
//
builder.RequireClaim(
XCustomClaims.IsBanned,
false.ToString(),
false.ToString().ToNormalString()
);
//
builder.RequireClaim(
XCustomClaims.IsEnabled,
true.ToString(),
true.ToString().ToNormalString()
);
}
//
// Nothing Required => at least Deny Anonymous to avoid an Empty Policy ...
if (!builder.Requirements.HasChild())
{
builder.RequireAuthenticatedUser();
}
//
return builder.Build();
}
}
}
+12 -2
View File
@@ -11,7 +11,17 @@ namespace xIdentityService.Extensions
/// </summary> /// </summary>
/// <param name="source"></param> /// <param name="source"></param>
/// <returns></returns> /// <returns></returns>
public static string ExtractApiKey(HttpRequest source) public static string ExtractApiKey(this HttpContext source)
{
return source.Request.ExtractApiKey();
}
/// <summary>
/// Extract ApiKey from Request Headers ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string ExtractApiKey(this HttpRequest source)
{ {
// //
var key = XHeader.ApiKey.GetStringValue(); var key = XHeader.ApiKey.GetStringValue();
@@ -24,7 +34,7 @@ namespace xIdentityService.Extensions
/// </summary> /// </summary>
/// <param name="source"></param> /// <param name="source"></param>
/// <returns></returns> /// <returns></returns>
public static string ExtractClientIP(HttpRequest source) public static string ExtractClientIP(this HttpRequest source)
{ {
// //
var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString(); var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString();
+66
View File
@@ -0,0 +1,66 @@
using System.Linq;
using xCommons.Extensions;
using System.Security.Claims;
using xIdentityModels.Models;
using System.Threading.Tasks;
using System.Text.Encodings.Web;
using System.Collections.Generic;
using xIdentityService.Constants;
using xIdentityModels.Extensions;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication;
namespace xIdentityService.Handlers
{
public class XApiKeyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IXIdentityProvider identityProvider;
public XApiKeyAuthenticationHandler(
UrlEncoder encoder,
ILoggerFactory logger,
ISystemClock systemClock,
IXIdentityProvider identityProvider,
IOptionsMonitor<AuthenticationSchemeOptions> options
) : base(options, logger, encoder, systemClock)
{
this.identityProvider = identityProvider;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//
var header = XHeader.ApiKey.GetStringValue();
if (!Request.Headers.TryGetValue(header, out var raw) ||
raw.ToString().IsNullOrEmpty())
{
return await Task.FromResult(AuthenticateResult.NoResult());
}
//
var response = await identityProvider.ValidateApiKey(new XApiKeyValidationRequest
{
ApiKey = raw.ToString(),
ClientIP = Context.Connection.RemoteIpAddress?.ToString()
}, Context.RequestAborted);
//
if (response.Errors.HasChild())
{
//
return await Task.FromResult(
AuthenticateResult.Fail(string.Join(",", response.Errors)));
}
//
var identity = new ClaimsIdentity(response.ToXClaims(), Scheme.Name);
var principal = new ClaimsPrincipal(identity);
//
return await Task.FromResult(AuthenticateResult.Success(
new AuthenticationTicket(principal, Scheme.Name)));
}
}
}
+12
View File
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Interfaces
{
public interface IXAuthorizationCache
{
void Clear();
void RemovePolicy(string name);
void SetPolicy(string name, AuthorizationPolicy policy);
bool TryGetPolicy(string name, out AuthorizationPolicy policy);
}
}
+118
View File
@@ -0,0 +1,118 @@
using xModels.Dtos;
using System.Threading;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xIdentityService.Models;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXAuthorizationProvider
{
//
#region Scope ...
Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
XQuery query,
CancellationToken cancellationToken = default
);
Task<XScopeDefinitionDto> GetScopeAsync(
string name,
CancellationToken cancellationToken = default
);
Task<XScopeDefinitionDto> AddScopeAsync(
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<XScopeDefinitionDto> UpdateScopeAsync(
string name,
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<bool> RemoveScopeAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
#endregion
//
#region Role ...
Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
CancellationToken cancellationToken = default
);
Task<XRoleDefinitionDto> GetRoleAsync(
string name,
CancellationToken cancellationToken = default
);
Task<XRoleDefinitionDto> AddRoleAsync(
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<XRoleDefinitionDto> UpdateRoleAsync(
string name,
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<bool> RemoveRoleAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<int> CountUsersInRoleAsync(
string name,
CancellationToken cancellationToken = default
);
Task<XQueryResult<XRoleDefinitionDto>> QueryRolesAsync(
XQuery query,
CancellationToken cancellationToken = default
);
#endregion
//
#region Policy ...
Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
XQuery query,
CancellationToken cancellationToken = default
);
Task<XPolicyDefinitionDto> GetPolicyAsync(
string name,
CancellationToken cancellationToken = default
);
Task<XPolicyDefinitionDto> AddPolicyAsync(
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<XPolicyDefinitionDto> UpdatePolicyAsync(
string name,
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<bool> RemovePolicyAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
string name,
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
);
Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
);
#endregion
//
#region Utilities ...
Task InvalidateAsync(string policyName = null);
#endregion
}
}
+55
View File
@@ -0,0 +1,55 @@
using RestSharp;
using System.Threading;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityService.Models;
using xHttpService.Interfaces;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public partial interface IXIdentityHttpProvider : IXHttpProvider
{
/// <summary>
/// Get an Instance of RestRequest ...
/// </summary>
/// <param name="endpoint"></param>
/// <param name="addXPoweredValue"></param>
/// <param name="params"></param>
/// <param name="headers"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
RestRequest GetRestRequest(
string endpoint,
bool addXPoweredValue = true,
IDictionary<string, string> @params = null,
IDictionary<string, string> headers = null,
IDictionary<string, string> queryStrings = null
);
/// <summary>
/// Handle Call Specific Request and retrieve Response
/// </summary>
/// <param name="client"></param>
/// <param name="request"></param>
/// <param name="method"></param>
/// <param name="supportRefreshingTokens"></param>
/// <param name="cancellationToken"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
Task<T> RunRestRequest<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
Task<XBaseRestResponse<T>> RunRestRequestByResponse<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
}
}
+33
View File
@@ -44,6 +44,7 @@ namespace xIdentityService.Interfaces
#region Authentication ... #region Authentication ...
Task<DiscoveryDocumentResponse> RequestDiscoveryDocument(); Task<DiscoveryDocumentResponse> RequestDiscoveryDocument();
Task<XTokenResponse> RequestScopeAccessToken(string scope); Task<XTokenResponse> RequestScopeAccessToken(string scope);
Task<TokenIntrospectionResponse> Validate(XTokenResponse model);
Task<TokenIntrospectionResponse> Introspection(XTokenResponse model); Task<TokenIntrospectionResponse> Introspection(XTokenResponse model);
Task<XLoginResponse> Login(XLoginRequest model); Task<XLoginResponse> Login(XLoginRequest model);
Task Logout(XTokenResponse model); Task Logout(XTokenResponse model);
@@ -321,6 +322,32 @@ namespace xIdentityService.Interfaces
XOpenActionInnerDto model XOpenActionInnerDto model
); );
//
Task<Guid> GetApiKey(
XDeviceDto device,
string apiKey
);
Task<Guid> GetApiKey(
XOpenActionInnerDto dto
);
Task<Guid> GetApiKey(
string token,
string request
);
//
Task<bool> UseApiKey(
XDeviceDto device,
XApiKeyUsageDto apiKeyUsage
);
Task<bool> UseApiKey(
XOpenActionInnerDto dto
);
Task<bool> UseApiKey(
string token,
string request
);
// //
Task<XOpenActionUserInfoDto> GetUserInfo( Task<XOpenActionUserInfoDto> GetUserInfo(
XDeviceDto device, XDeviceDto device,
@@ -369,11 +396,13 @@ namespace xIdentityService.Interfaces
/// Update Specified Application ... /// Update Specified Application ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<XApplicationDto> UpdateApplication( Task<XApplicationDto> UpdateApplication(
XTokenResponse tokens, XTokenResponse tokens,
int id,
XApplicationDto item, XApplicationDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
@@ -461,11 +490,13 @@ namespace xIdentityService.Interfaces
/// Update Specified ApiKey ... /// Update Specified ApiKey ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<XApiKeyDto> UpdateApiKey( Task<XApiKeyDto> UpdateApiKey(
XTokenResponse tokens, XTokenResponse tokens,
Guid id,
XApiKeyDto item, XApiKeyDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
@@ -540,11 +571,13 @@ namespace xIdentityService.Interfaces
/// Update Specified Api Key Usage ... /// Update Specified Api Key Usage ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
Task<XApiKeyUsageDto> UpdateApiKeyUsage( Task<XApiKeyUsageDto> UpdateApiKeyUsage(
XTokenResponse tokens, XTokenResponse tokens,
long id,
XApiKeyUsageDto item, XApiKeyUsageDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
+20
View File
@@ -0,0 +1,20 @@
using xModels.Dtos;
using System.Threading.Tasks;
namespace xIdentityService.Interfaces
{
public interface IXPersonService
{
/// <summary>
/// Retrieve Person ...
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<XPersonDto> GetPerson(string userId);
/// <summary>
/// Handle Cleanup ...
/// </summary>
void Cleanup();
}
}
+43
View File
@@ -0,0 +1,43 @@
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXPolicyHandler
{
/// <summary>
/// Add Specified Role ...
/// </summary>
/// <param name="policy"></param>
/// <param name="requiredRoles"></param>
/// <returns></returns>
bool AddPolicy(
string policy,
IEnumerable<string> requiredRoles
);
/// <summary>
/// Check Specified Role Exists or not ...
/// </summary>
/// <param name="policy"></param>
/// <returns></returns>
bool HasPolicy(string policy);
/// <summary>
/// Remove Specified Role ...
/// </summary>
/// <param name="policy"></param>
/// <returns></returns>
bool RemovePolicy(string policy);
/// <summary>
/// Check Specified Policy passed or not ...
/// </summary>
/// <param name="policy"></param>
/// <param name="roles"></param>
/// <returns></returns>
bool IsPolicyPassed(
string policy,
IEnumerable<string> roles
);
}
}
+247
View File
@@ -0,0 +1,247 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXPolicyProvider
{
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
IQueryable<XPolicyDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null
);
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XPolicyDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> FindOneAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XPolicyDefinitionDto>> FindManyAsync(
Expression<Func<XPolicyDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XQueryResult<XPolicyDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XPolicyDefinition, bool>> predicate = null,
Func<IQueryable<XPolicyDefinition>, IOrderedQueryable<XPolicyDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> AddAsync(
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> UpdateAsync(
int id,
XPolicyDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Custom ...
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinition source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XPolicyDefinitionDto> EnrichAsync(
XPolicyDefinitionDto source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinition> sources,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XPolicyDefinitionDto>> EnrichRangeAsync(
IEnumerable<XPolicyDefinitionDto> sources,
CancellationToken cancellationToken = default
);
#endregion
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXRoleHierarchyResolver
{
/// <summary>
/// Retrieve All Enabled Role Names which Weight >= minWeight ...
/// </summary>
/// <param name="minWeight"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<string>> GetRolesByMinWeightAsync(
int minWeight,
CancellationToken cancellationToken = default
);
/// <summary>
/// Retrieve Effective Roles for a Policy
/// (explicit RequiredRoles ∪ roles by MinRoleWeight ∪ parents chain) ...
/// </summary>
/// <param name="explicitRoles"></param>
/// <param name="minRoleWeight"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
IEnumerable<string> explicitRoles,
int? minRoleWeight,
CancellationToken cancellationToken = default
);
}
}
+247
View File
@@ -0,0 +1,247 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXRoleProvider
{
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
IQueryable<XRoleDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null
);
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XRoleDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> FindOneAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XRoleDefinitionDto>> FindManyAsync(
Expression<Func<XRoleDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XQueryResult<XRoleDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XRoleDefinition, bool>> predicate = null,
Func<IQueryable<XRoleDefinition>, IOrderedQueryable<XRoleDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> AddAsync(
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> UpdateAsync(
int id,
XRoleDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Custom ...
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinition source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XRoleDefinitionDto> EnrichAsync(
XRoleDefinitionDto source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinition> sources,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XRoleDefinitionDto>> EnrichRangeAsync(
IEnumerable<XRoleDefinitionDto> sources,
CancellationToken cancellationToken = default
);
#endregion
}
}
+247
View File
@@ -0,0 +1,247 @@
using System;
using xModels.Dtos;
using System.Linq;
using System.Threading;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXScopeProvider
{
//
#region Readers ...
/// <summary>
/// retrieve whole items as queryable ...
/// </summary>
/// <param name="asNoTracking">a flag for Tracking behaviour</param>
/// <param name="predicate">an Expression for Filter Items ...</param>
/// <param name="orderBuilder">an Order Builder expression for Ordering Query ...</param>
/// <returns></returns>
IQueryable<XScopeDefinition> AsQueryable(
bool asNoTracking = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null
);
/// <summary>
/// retrieve an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// retrieve all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XScopeDefinitionDto>> GetAllAsync(
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// find an Entity by providing a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> FindOneAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// find a collection of Entities by proving a Conditional Expression ...
/// </summary>
/// <param name="predicate"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XScopeDefinitionDto>> FindManyAsync(
Expression<Func<XScopeDefinition, bool>> predicate,
bool ignoreSoftDeleteds = true,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities ...
/// </summary>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> CountAsync(
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// count all exists Entities Pages by providing page size ...
/// </summary>
/// <param name="pageSize"></param>
/// <param name="totalItems"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<int> PagesCountAsync(
int pageSize,
int? totalItems = null,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
/// <summary>
/// Check an Entity exists or not ...
/// </summary>
/// <param name="id"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<bool> IsExistsAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
#endregion
//
#region Query ...
/// <summary>
/// retrieve Entities based on XQuery Pagination structure ...
/// </summary>
/// <param name="query"></param>
/// <param name="ignoreSoftDeleteds"></param>
/// <param name="predicate"></param>
/// <param name="orderBuilder"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XQueryResult<XScopeDefinitionDto>> QueryAsync(
XQuery query,
bool ignoreSoftDeleteds = true,
Expression<Func<XScopeDefinition, bool>> predicate = null,
Func<IQueryable<XScopeDefinition>, IOrderedQueryable<XScopeDefinition>> orderBuilder = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Add/Update/Remove ...
/// <summary>
/// add a new Entity ...
/// </summary>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> AddAsync(
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// Update an Entity values ...
/// </summary>
/// <param name="id"></param>
/// <param name="item"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> UpdateAsync(
int id,
XScopeDefinitionDto item,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
/// <summary>
/// remove an Entity by it's Id ...
/// </summary>
/// <param name="id"></param>
/// <param name="softDelete"></param>
/// <param name="saveChanges"></param>
/// <param name="userInfo"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> RemoveAsync(
int id,
bool softDelete = true,
bool saveChanges = true,
XUserClaimsInfoDto userInfo = null,
CancellationToken cancellationToken = default
);
#endregion
//
#region Custom ...
#endregion
//
#region Enrichers ...
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinition source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich Item ...
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<XScopeDefinitionDto> EnrichAsync(
XScopeDefinitionDto source,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinition> sources,
CancellationToken cancellationToken = default
);
/// <summary>
/// Enrich a Collection of Items(s) ...
/// </summary>
/// <param name="sources"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<XScopeDefinitionDto>> EnrichRangeAsync(
IEnumerable<XScopeDefinitionDto> sources,
CancellationToken cancellationToken = default
);
#endregion
}
}
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.Diagnostics;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using xIdentityService.Attributes;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Features;
namespace xIdentityService.Middlewares
{
public class XApiKeyUsageMiddleware
{
//
#region Properties ...
private readonly RequestDelegate next;
#endregion
//
#region Constructor ...
public XApiKeyUsageMiddleware(
RequestDelegate next
)
{
this.next = next;
}
#endregion
//
#region Actions ...
public async Task InvokeAsync(
HttpContext context,
IXIdentityProvider identityProvider
)
{
//
// Check Context Has ApiKey Authorization Filter ...
var endpointFeature = context.Features.Get<IEndpointFeature>();
var endpoint =
endpointFeature.IsNull()
? null
: endpointFeature.Endpoint;
var apiKeyAccessAttibute =
endpoint.IsNull()
? null
: endpoint.Metadata.GetMetadata<XApiKeyAccessAttribute>();
if (!apiKeyAccessAttibute.IsNull())
{
//
var sw = Stopwatch.StartNew();
var requestedOn = DateTime.UtcNow;
var httpMethod = context.Request.Method;
var statusCode = StatusCodes.Status200OK;
var endpointName = context.GetRequestPath();
var clientIp = context.Request.ExtractClientIP();
//
var device = identityProvider.GetDevice();
var apiKey = context.Request.ExtractApiKey();
var cApiKeyId = context.Request.HttpContext.User.Identity;
var apiKeyId = await identityProvider.GetApiKey(
device: device,
apiKey: apiKey
);
//
try
{
await next(context);
statusCode = context.Response.StatusCode;
}
catch
{
statusCode = StatusCodes.Status500InternalServerError;
throw;
}
//
sw.Stop();
var dto = new XApiKeyUsageDto
{
ApiKeyId = apiKeyId,
ClientIP = clientIp,
Endpoint = endpointName,
StatusCode = statusCode,
HttpMethod = httpMethod,
RequestedOn = requestedOn,
ResponseTimeMs = sw.ElapsedMilliseconds,
};
await identityProvider.UseApiKey(
device: device,
apiKeyUsage: dto
);
}
else
{
await next(context);
}
}
#endregion
}
public static class XApiKeyUsageMiddlewareDIExtensions
{
/// <summary>
/// Adding XProxy Middleware to Applications ...
/// </summary>
/// <param name="app"></param>
public static void UseXApiKeyUsage(this IApplicationBuilder app)
{
app.UseMiddleware<XApiKeyUsageMiddleware>();
}
}
}
+4 -4
View File
@@ -42,12 +42,12 @@ namespace xIdentityService.Middlewares {
IHttpClientFactory httpClientFactory IHttpClientFactory httpClientFactory
) : base (loggerFactory) { ) : base (loggerFactory) {
// //
this.CONFIGURATION = configuration; CONFIGURATION = configuration;
this.NEXT_MIDDLEWARE = nextMiddleware; NEXT_MIDDLEWARE = nextMiddleware;
// //
// Create Http Client ... // Create Http Client ...
this.HTTP_CLIENT = httpClientFactory HTTP_CLIENT = httpClientFactory
.CreateClient (XProxyConstants.XPROXY_HTTP_CLIENT); .CreateClient (XProxyConstants.XPROXY_HTTP_CLIENT);
// //
@@ -547,7 +547,7 @@ namespace xIdentityService.Middlewares {
/// Processing Response Content and Handle it on HttpContextResponse ... /// Processing Response Content and Handle it on HttpContextResponse ...
/// </summary> /// </summary>
/// <param name="context"></param> /// <param name="context"></param>
/// <param name="response"></param> /// <param name="message"></param>
/// <returns></returns> /// <returns></returns>
private async Task ProcessResponseContent ( private async Task ProcessResponseContent (
HttpContext context, HttpContext context,
+76
View File
@@ -0,0 +1,76 @@
using System;
using xCommons.Extensions;
using xExceptions.Constants;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Models
{
public class XAuthorizationCache : IXAuthorizationCache
{
private readonly ILogger<XAuthorizationCache> logger;
private readonly ConcurrentDictionary<string, AuthorizationPolicy> policies;
public XAuthorizationCache(
ILogger<XAuthorizationCache> logger
)
{
//
this.logger = logger;
policies = new ConcurrentDictionary<string, AuthorizationPolicy>(StringComparer.Ordinal);
}
public void Clear()
{
policies.Clear();
}
public void SetPolicy(
string name,
AuthorizationPolicy policy
)
{
//
if (name.IsNullOrEmpty() ||
policy.IsNullOrDefault())
{
XException.InvalidArgs.Throw();
}
//
policies.AddOrUpdate(name, policy, (_, __) => policy);
}
public bool TryGetPolicy(
string name,
out AuthorizationPolicy policy
)
{
//
if (name.IsNullOrEmpty())
{
//
policy = null!;
return false;
}
//
var result = policies.TryGetValue(name, out policy!);
return result;
}
public void RemovePolicy(string name)
{
//
if (name.IsNullOrEmpty())
{
return;
}
//
if (policies.TryRemove(name, out _)) { }
}
}
}
+38
View File
@@ -0,0 +1,38 @@
using System.Collections.Generic;
namespace xIdentityService.Models
{
public class XEffectiveAuthorizationDto
{
/// <summary>
/// Policy Name ...
/// </summary>
public string PolicyName { get; set; }
/// <summary>
/// Required Authenticated User ...
/// </summary>
public bool RequireAuthenticatedUser { get; set; }
/// <summary>
/// Check Policy has Enabled feature or not ...
/// (IsEnabled/IsBanned) ...
/// </summary>
public bool RequireEnabledUser { get; set; }
/// <summary>
/// Effective Roles ...
/// </summary>
public HashSet<string> EffectiveRoles { get; set; } = [];
/// <summary>
/// Effective Scopes ...
/// </summary>
public HashSet<string> EffectiveScopes { get; set; } = [];
/// <summary>
/// Effective Claims ...
/// </summary>
public List<XRequiredClaimDto> EffectiveClaims { get; set; } = [];
}
}
+11
View File
@@ -0,0 +1,11 @@
using System.Collections.Generic;
namespace xIdentityService.Models
{
public class XPolicyEvaluationResultDto
{
public bool Passed { get; set; }
public string Policy { get; set; }
public List<string> FailedRequirements { get; set; } = [];
}
}
+10
View File
@@ -0,0 +1,10 @@
using System.Collections.Generic;
namespace xIdentityService.Models
{
public class XRequiredClaimDto
{
public string Type { get; set; }
public List<string> Values { get; set; }
}
}
+297
View File
@@ -0,0 +1,297 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xIdentityService.Models;
using System.Collections.Generic;
using xIdentityService.Extensions;
namespace xIdentityService.Providers
{
public partial class XAuthorizationProvider
{
// //
// #region Policy ...
// public async Task<XPolicyDefinitionDto> AddPolicyAsync(
// XPolicyDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (item.IsNull() || item.Name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var normalized = item.Name.ToNormalString();
// var exists = await policies.FindOneAsync(
// predicate: p => p.Name.ToLower() == normalized,
// cancellationToken: cancellationToken
// );
// if (!exists.IsNull())
// {
// XException.Duplicate.Throw();
// }
// //
// await ValidateReferencesAsync(item, cancellationToken);
// //
// item.IsSystem = false;
// //
// var result = await policies.AddAsync(
// item: item,
// cancellationToken: cancellationToken
// );
// //
// await InvalidateAsync(result.Name);
// //
// return result;
// }
// public async Task<bool> RemovePolicyAsync(
// string name,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// var entity = await FindPolicyOrThrowAsync(name, cancellationToken);
// if (entity.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// await policies.RemoveAsync(
// id: entity.Id,
// cancellationToken: cancellationToken
// );
// //
// await InvalidateAsync(entity.Name);
// return true;
// }
// public async Task<XQueryResult<XPolicyDefinitionDto>> QueryPoliciesAsync(
// XQuery query,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (query.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var result = await policies.QueryAsync(
// query: query,
// cancellationToken: cancellationToken
// );
// //
// return result;
// }
// public async Task<XPolicyDefinitionDto> GetPolicyAsync(
// string name,
// CancellationToken cancellationToken = default
// )
// {
// //
// var result = await FindPolicyOrThrowAsync(name, cancellationToken);
// //
// return result;
// }
// public async Task<XPolicyDefinitionDto> UpdatePolicyAsync(
// string name,
// XPolicyDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (name.IsNullOrEmpty() || item.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var exists = await FindPolicyOrThrowAsync(name, cancellationToken);
// if (exists.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// // Referenced Roles & Scopes must exist ...
// await ValidateReferencesAsync(item, cancellationToken);
// //
// var result = await policies.UpdateAsync(
// item: item,
// id: exists.Id,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Drop the cached policy so it rebuilds on next evaluation ...
// await InvalidateAsync(result.Name);
// //
// // Return the updated DTO as-is (EffectiveRoles is not a field on
// // XPolicyDefinitionDto) ...
// return result;
// }
// public async Task<XPolicyEvaluationResultDto> EvaluatePolicyAsync(
// string name,
// XUserClaimsInfoDto target,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Load the policy (throws NotFound when missing) ...
// var dto = await FindPolicyOrThrowAsync(name, cancellationToken);
// //
// var result = new XPolicyEvaluationResultDto
// {
// Passed = true,
// Policy = dto.Name,
// FailedRequirements = []
// };
// //
// // Build the policy's effective authorization via the shared helper
// // (resolver + projection onto XEffectiveAuthorizationDto) ...
// var auth = await ToDtoWithEffectiveRolesAsync(dto, cancellationToken);
// if (auth.IsNull())
// {
// //
// result.Passed = false;
// result.FailedRequirements.Add("PolicyNotBuilt");
// //
// return result;
// }
// //
// // Anonymous user fails any policy that requires authentication ...
// if (target.IsNull())
// {
// //
// if (auth.RequireAuthenticatedUser)
// {
// //
// result.Passed = false;
// result.FailedRequirements.Add("RequireAuthenticatedUser");
// }
// //
// return result;
// }
// //
// // Effective Roles: the user must hold at least one ...
// if (auth.EffectiveRoles.HasChild())
// {
// //
// // var userRoles = await roles.FindManyAsync(
// // target.GetUserSelectByParam(),
// // cancellationToken
// // );
// //
// var userSelectByParam = target.GetUserSelectByParam();
// //
// var userRoles = await roles.FindManyAsync(
// predicate: x => x.
// cancellationToken: cancellationToken
// );
// //
// var matched = auth.EffectiveRoles.Any(er =>
// userRoles.Any(ur =>
// string.Equals(ur, er, StringComparison.OrdinalIgnoreCase)
// )
// );
// //
// if (!matched)
// {
// //
// result.Passed = false;
// result.FailedRequirements.Add("RequiredRoles");
// }
// }
// //
// // NOTE: RequireEnabledUser (IsEnabled / !IsBanned), EffectiveScopes and
// // EffectiveClaims checks are layered on here once the matching flags /
// // collections on XUserClaimsInfoDto (xIdentityModels) are wired.
// return result;
// }
// public async Task<XEffectiveAuthorizationDto> GetEffectiveAuthorizationAsync(
// XUserClaimsInfoDto target,
// CancellationToken cancellationToken = default
// )
// {
// //
// var result = new XEffectiveAuthorizationDto
// {
// RequireEnabledUser = !target.IsNull(),
// RequireAuthenticatedUser = !target.IsNull(),
// EffectiveClaims = new List<XRequiredClaimDto>(),
// EffectiveRoles = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
// EffectiveScopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase),
// };
// //
// if (target.IsNull())
// {
// return result;
// }
// //
// // Effective roles = the user's actual roles (from RoleManager) ...
// var userRoles = await roleSync.GetUserRolesAsync(
// cancellationToken: cancellationToken,
// userSelectByParam: target.GetUserSelectByParam()
// );
// foreach (var role in userRoles)
// {
// result.EffectiveRoles.Add(role);
// }
// //
// // NOTE: EffectiveScopes / EffectiveClaims aggregation is wired here from
// // the user's scope / claim source on XUserClaimsInfoDto (xIdentityModels).
// return result;
// }
// #endregion
// //
// #region Private ...
// #endregion
}
}
+181
View File
@@ -0,0 +1,181 @@
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Providers
{
public partial class XAuthorizationProvider
{
//
// #region Role ...
// public async Task<IEnumerable<XRoleDefinitionDto>> GetRolesAsync(
// CancellationToken cancellationToken = default
// )
// {
// //
// var result = await roles
// .GetAllAsync(cancellationToken: cancellationToken);
// //
// return result;
// }
// public async Task<XRoleDefinitionDto> GetRoleAsync(
// string name,
// CancellationToken cancellationToken = default
// )
// {
// //
// var result = await FindRoleOrThrowAsync(name, cancellationToken);
// //
// return result;
// }
// public async Task<XRoleDefinitionDto> AddRoleAsync(
// XRoleDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (item.IsNull() || item.Name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// // Duplicate check ...
// var normalized = item.Name.ToNormalString();
// var exists = await roles.FindOneAsync(
// predicate: r => r.Name.ToLower() == normalized,
// cancellationToken: cancellationToken
// );
// if (!exists.IsNull())
// {
// XException.Duplicate.Throw();
// }
// //
// // Persist ...
// item.IsSystem = false;
// var result = await roles.AddAsync(
// item: item,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Sync to IdentityServer (RoleManager<IdentityRole>) ...
// var entity = roles.AsQueryable()
// .FirstOrDefault(r => r.Name.ToLower() == normalized);
// if (!entity.IsNull())
// {
// await roleSync.UpsertAsync(entity, cancellationToken);
// }
// //
// await InvalidateAsync();
// return result;
// }
// public async Task<XRoleDefinitionDto> UpdateRoleAsync(
// string name,
// XRoleDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (name.IsNullOrEmpty() || item.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var existing = await FindRoleOrThrowAsync(name, cancellationToken);
// if (existing.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// var updated = await roles.UpdateAsync(
// id: existing.Id,
// item: item,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Sync to IdentityServer ...
// var entity = roles.AsQueryable()
// .FirstOrDefault(r => r.Name.ToLower() == name.ToNormalString());
// if (!entity.IsNull())
// {
// await roleSync.UpsertAsync(entity, cancellationToken);
// }
// //
// await InvalidateAsync();
// return updated;
// }
// public async Task<bool> RemoveRoleAsync(
// string name,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// var exists = await FindRoleOrThrowAsync(name, cancellationToken);
// if (exists.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// await roles.RemoveAsync(
// id: exists.Id,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Remove from IdentityServer ...
// await roleSync.RemoveAsync(name, cancellationToken);
// //
// await InvalidateAsync();
// return true;
// }
// public async Task<int> CountUsersInRoleAsync(
// string name,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Fail fast if the role itself does not exist ...
// await FindRoleOrThrowAsync(name, cancellationToken);
// //
// var result = await roleSync
// .CountUsersInRoleAsync(
// name,
// cancellationToken
// );
// //
// return result;
// }
// #endregion
}
}
+174
View File
@@ -0,0 +1,174 @@
using System;
using System.Linq;
using xModels.Dtos;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Providers
{
public partial class XAuthorizationProvider
{
// //
// #region Scope ...
// public async Task<XQueryResult<XScopeDefinitionDto>> QueryScopesAsync(
// XQuery query,
// CancellationToken cancellationToken = default
// )
// {
// //
// if (query.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var result = await scopes.QueryAsync(
// query: query,
// cancellationToken: cancellationToken
// );
// //
// return result;
// }
// public async Task<XScopeDefinitionDto> GetScopeAsync(
// string name,
// CancellationToken cancellationToken = default
// )
// {
// //
// var result = await FindScopeOrThrowAsync(name, cancellationToken);
// //
// return result;
// }
// public async Task<XScopeDefinitionDto> AddScopeAsync(
// XScopeDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (item.IsNull() || item.Name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// // Duplicate check ...
// var normalized = item.Name.ToNormalString();
// var exists = await scopes.FindOneAsync(
// cancellationToken: cancellationToken,
// predicate: s => s.Name.ToLower() == normalized
// );
// if (!exists.IsNull())
// {
// XException.Duplicate.Throw();
// }
// //
// // Persist ...
// item.IsSystem = false;
// var result = await scopes.AddAsync(
// item: item,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Sync to IdentityServer (ConfigurationDbContext) ...
// var entity = scopes.AsQueryable()
// .FirstOrDefault(s => s.Name.ToLower() == normalized);
// if (!entity.IsNull())
// {
// //
// await scopeSync
// .UpsertAsync(entity, cancellationToken);
// }
// //
// await InvalidateAsync();
// return result;
// }
// public async Task<XScopeDefinitionDto> UpdateScopeAsync(
// string name,
// XScopeDefinitionDto item,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Validate ...
// if (name.IsNullOrEmpty() || item.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var existing = await FindScopeOrThrowAsync(name, cancellationToken);
// if (existing.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// var updated = await scopes.UpdateAsync(
// id: existing.Id,
// item: item,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Sync to IdentityServer ...
// var entity = scopes.AsQueryable()
// .FirstOrDefault(s => s.Name.ToLower() == name.ToNormalString());
// if (!entity.IsNull())
// {
// await scopeSync.UpsertAsync(entity, cancellationToken);
// }
// //
// await InvalidateAsync();
// return updated;
// }
// public async Task<bool> RemoveScopeAsync(
// string name,
// XUserClaimsInfoDto userInfo,
// CancellationToken cancellationToken = default
// )
// {
// //
// var entity = await FindScopeOrThrowAsync(name, cancellationToken);
// if (entity.IsSystem)
// {
// XException.NotAllowed.Throw();
// }
// //
// await scopes.RemoveAsync(
// id: entity.Id,
// userInfo: userInfo,
// cancellationToken: cancellationToken
// );
// //
// // Remove from IdentityServer ...
// await scopeSync.RemoveAsync(name, cancellationToken);
// //
// await InvalidateAsync();
// return true;
// }
// #endregion
}
}
+47 -25
View File
@@ -7,16 +7,14 @@ using xExceptions.Constants;
using System.Threading.Tasks; using System.Threading.Tasks;
using xIdentityModels.Models; using xIdentityModels.Models;
using xHttpService.Constants; using xHttpService.Constants;
using xHttpService.Extensions;
using System.Collections.Generic; using System.Collections.Generic;
using xIdentityService.Constants; using xIdentityService.Constants;
using xHttpService.Extensions;
using MongoDB.Bson;
namespace xIdentityService.Providers namespace xIdentityService.Providers
{ {
public partial class XIdentityProvider public partial class XIdentityProvider
{ {
// //
#region Applications ... #region Applications ...
// //
@@ -65,11 +63,13 @@ namespace xIdentityService.Providers
/// Update Specified Application ... /// Update Specified Application ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<XApplicationDto> UpdateApplication( public async Task<XApplicationDto> UpdateApplication(
XTokenResponse tokens, XTokenResponse tokens,
int id,
XApplicationDto item, XApplicationDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -84,12 +84,21 @@ namespace xIdentityService.Providers
tokens.AccessToken tokens.AccessToken
) )
.ValidateGroupAsync(); .ValidateGroupAsync();
if (!id.IsValidIntId())
{
XException.InvalidArgs.Throw();
}
// //
var client = GetRestClient(tokens); var client = GetRestClient(tokens);
// //
var request = GetRestRequet(XApiAccountEndpoint.UpdateApplication); var request = GetRestRequet(
XApiAccountEndpoint.UpdateApplication,
@params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() }
}
);
request.AddJsonBody(item); request.AddJsonBody(item);
// //
@@ -181,7 +190,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.GetApplication, XApiAccountEndpoint.GetApplication,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
@@ -227,7 +236,7 @@ namespace xIdentityService.Providers
// //
// Attach XQuery to Request ... // Attach XQuery to Request ...
request = request.AttachXQuery (query); request = request.AttachXQuery(query);
// //
var response = await RunRestRequest<XQueryResult<XApplicationDto>>( var response = await RunRestRequest<XQueryResult<XApplicationDto>>(
@@ -307,7 +316,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.GetApiKey, XApiAccountEndpoint.GetApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
@@ -351,7 +360,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.RemoveApiKey, XApiAccountEndpoint.RemoveApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
@@ -369,11 +378,13 @@ namespace xIdentityService.Providers
/// Update Specified ApiKey ... /// Update Specified ApiKey ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<XApiKeyDto> UpdateApiKey( public async Task<XApiKeyDto> UpdateApiKey(
XTokenResponse tokens, XTokenResponse tokens,
Guid id,
XApiKeyDto item, XApiKeyDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -382,12 +393,17 @@ namespace xIdentityService.Providers
// Validate Args ... // Validate Args ...
await validationProvider await validationProvider
.GroupValidationBuilder() .GroupValidationBuilder()
.AddIsGuid(id)
.AddNotNull(item) .AddNotNull(item)
.AddNotNull(tokens) .AddNotNull(tokens)
.AddNotEmpty( .AddNotEmpty(
tokens.AccessToken tokens.AccessToken
) )
.ValidateGroupAsync(); .ValidateGroupAsync();
if (id != item.Id)
{
XException.InvalidArgs.Throw();
}
// //
var client = GetRestClient(tokens); var client = GetRestClient(tokens);
@@ -395,8 +411,8 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.UpdateApiKey, XApiAccountEndpoint.UpdateApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), item.Id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
request.AddJsonBody(item); request.AddJsonBody(item);
@@ -442,7 +458,7 @@ namespace xIdentityService.Providers
// //
// Attach XQuery to Request ... // Attach XQuery to Request ...
request = request.AttachXQuery (query); request = request.AttachXQuery(query);
// //
var response = await RunRestRequest<XQueryResult<XApiKeyDto>>( var response = await RunRestRequest<XQueryResult<XApiKeyDto>>(
@@ -565,7 +581,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.GetApiKeyUsage, XApiAccountEndpoint.GetApiKeyUsage,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
@@ -612,7 +628,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.RemoveApiKeyUsage, XApiAccountEndpoint.RemoveApiKeyUsage,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XId.GetStringValue (), id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
@@ -630,11 +646,13 @@ namespace xIdentityService.Providers
/// Update Specified Api Key Usage ... /// Update Specified Api Key Usage ...
/// </summary> /// </summary>
/// <param name="tokens"></param> /// <param name="tokens"></param>
/// <param name="id"></param>
/// <param name="item"></param> /// <param name="item"></param>
/// <param name="cancellationToken"></param> /// <param name="cancellationToken"></param>
/// <returns></returns> /// <returns></returns>
public async Task<XApiKeyUsageDto> UpdateApiKeyUsage( public async Task<XApiKeyUsageDto> UpdateApiKeyUsage(
XTokenResponse tokens, XTokenResponse tokens,
long id,
XApiKeyUsageDto item, XApiKeyUsageDto item,
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
) )
@@ -649,6 +667,9 @@ namespace xIdentityService.Providers
tokens.AccessToken tokens.AccessToken
) )
.ValidateGroupAsync(); .ValidateGroupAsync();
if (id <= 0 || id != item.Id) {
XException.InvalidArgs.Throw();
}
// //
var client = GetRestClient(tokens); var client = GetRestClient(tokens);
@@ -658,7 +679,7 @@ namespace xIdentityService.Providers
XApiAccountEndpoint.UpdateApiKeyUsage, XApiAccountEndpoint.UpdateApiKeyUsage,
@params: new Dictionary<string, string> @params: new Dictionary<string, string>
{ {
{ XParam.XId.GetStringValue (), item.Id.ToString() } { XParam.XId.GetStringValue (), id.ToString() }
} }
); );
request.AddJsonBody(item); request.AddJsonBody(item);
@@ -704,7 +725,7 @@ namespace xIdentityService.Providers
// //
// Attach XQuery to Request ... // Attach XQuery to Request ...
request = request.AttachXQuery (query); request = request.AttachXQuery(query);
// //
var response = await RunRestRequest<XQueryResult<XApiKeyUsageDto>>( var response = await RunRestRequest<XQueryResult<XApiKeyUsageDto>>(
@@ -790,7 +811,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.ShowApiKey, XApiAccountEndpoint.ShowApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() },
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
@@ -841,9 +862,9 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.CreateApiKey, XApiAccountEndpoint.CreateApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
); );
request.AddJsonBody(createRequest); request.AddJsonBody(createRequest);
@@ -891,8 +912,8 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.RemoveApiKey, XApiAccountEndpoint.RemoveApiKeyCustom,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() },
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
@@ -945,7 +966,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.RotateApiKey, XApiAccountEndpoint.RotateApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() },
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
@@ -997,7 +1018,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.RevokeApiKey, XApiAccountEndpoint.RevokeApiKey,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() },
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
@@ -1045,7 +1066,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.GetApiKeys, XApiAccountEndpoint.GetApiKeys,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
); );
@@ -1095,7 +1116,7 @@ namespace xIdentityService.Providers
// //
var request = GetRestRequet( var request = GetRestRequet(
XApiAccountEndpoint.GetApiKeyUsages, XApiAccountEndpoint.GetApiKeyUsages,
@params: new Dictionary<string, string> { @params: new Dictionary<string, string> {
{ XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() }, { XParam.XApiKeyId.GetStringValue (), apiKeyId.ToString() },
{ XParam.XApplicationId.GetStringValue (), applicationId.ToString() } { XParam.XApplicationId.GetStringValue (), applicationId.ToString() }
} }
@@ -1132,7 +1153,7 @@ namespace xIdentityService.Providers
var client = GetRestClient(); var client = GetRestClient();
// //
var checksum = SecurityProvider.Encrypt(validationRequest.ToJson()).ToMd5String(); var checksum = SecurityProvider.Encrypt(validationRequest.ToJSON()).ToMd5String();
// //
var request = GetRestRequet( var request = GetRestRequet(
@@ -1141,6 +1162,7 @@ namespace xIdentityService.Providers
{ XHeader.ChecksumDigest.GetStringValue(), checksum } { XHeader.ChecksumDigest.GetStringValue(), checksum }
} }
); );
request.AddJsonBody(validationRequest);
// //
var response = await RunRestRequest<XApiKeyValidationResult>( var response = await RunRestRequest<XApiKeyValidationResult>(
+174 -98
View File
@@ -9,33 +9,40 @@ using System.Collections.Generic;
using xIdentityModels.Extensions; using xIdentityModels.Extensions;
using xIdentityService.Constants; using xIdentityService.Constants;
namespace xIdentityService.Providers { namespace xIdentityService.Providers
public partial class XIdentityProvider { {
public partial class XIdentityProvider
{
// //
#region Authentication Handlers ... #region Authentication Handlers ...
/// <summary> /// <summary>
/// Request for Discovery Document /// Request for Discovery Document
/// </summary> /// </summary>
/// <returns>an instance of DiscoveryDocumentResponse</returns> /// <returns>an instance of DiscoveryDocumentResponse</returns>
public async Task<DiscoveryDocumentResponse> RequestDiscoveryDocument () { public async Task<DiscoveryDocumentResponse> RequestDiscoveryDocument()
{
// //
var httpClient = GetHttpClient (); var httpClient = GetHttpClient();
// //
try { try
{
// //
var result = httpClient var result = httpClient
.GetDiscoveryDocumentAsync (identityConfiguration.Authority) .GetDiscoveryDocumentAsync(identityConfiguration.Authority)
.ContinueWith (docTask => { .ContinueWith(docTask =>
{
// //
httpClient.Dispose (); httpClient.Dispose();
return docTask.Result; return docTask.Result;
}); });
// //
return await result; return await result;
} catch { }
throw XException.ActionFailed.ToException (); catch
{
throw XException.ActionFailed.ToException();
} }
} }
@@ -44,25 +51,29 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="scope">a member of <see>XApiScope</see></param> /// <param name="scope">a member of <see>XApiScope</see></param>
/// <returns>an instance of <see>XTokenResponse</see></returns> /// <returns>an instance of <see>XTokenResponse</see></returns>
public async Task<XTokenResponse> RequestScopeAccessToken (string scope) { public async Task<XTokenResponse> RequestScopeAccessToken(string scope)
{
// //
// Validate Args ... // Validate Args ...
var scopeName = string.Empty; var scopeName = string.Empty;
try { try
{
scopeName = scope; // scope.GetStringValue (); scopeName = scope; // scope.GetStringValue ();
} catch { } }
if (scopeName.IsNullOrEmpty ()) { catch { }
XException.InvalidArgs.Throw (); if (scopeName.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
} }
// //
var client = GetRestClient (); var client = GetRestClient();
var request = GetRestRequet ( var request = GetRestRequet(
XApiAccountEndpoint.RequestScopeAccessToken, XApiAccountEndpoint.RequestScopeAccessToken,
headers : new Dictionary<string, string> { { XParam.XScope.GetStringValue (), scope.ToString () } }); headers: new Dictionary<string, string> { { XParam.XScope.GetStringValue(), scope.ToString() } });
// //
var response = await RunRestRequest<XTokenResponse> ( var response = await RunRestRequest<XTokenResponse>(
client, client,
request, request,
XHttpMethod.POST XHttpMethod.POST
@@ -70,8 +81,9 @@ namespace xIdentityService.Providers {
// //
// Save Token ... // Save Token ...
if (!response.IsNull ()) { if (!response.IsNull())
await tokenProvider.AddOrUpdateToken (response); {
await tokenProvider.AddOrUpdateToken(response);
} }
// //
@@ -83,45 +95,100 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="model">Authentication Tokens</param> /// <param name="model">Authentication Tokens</param>
/// <returns>an instance of TokenIntrospectionResponse</returns> /// <returns>an instance of TokenIntrospectionResponse</returns>
public async Task<TokenIntrospectionResponse> Introspection (XTokenResponse model) { public async Task<TokenIntrospectionResponse> Introspection(XTokenResponse model)
{
// //
// Validate Args ... // Validate Args ...
await validationProvider await validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (model) .AddNotNull(model)
.AddNotEmpty (model.AccessToken) .AddNotEmpty(model.AccessToken)
.ValidateGroupAsync (); .ValidateGroupAsync();
// //
var httpClient = GetHttpClient (); var httpClient = GetHttpClient();
// //
try { try
{
// //
var discoDoc = await RequestDiscoveryDocument (); var discoDoc = await RequestDiscoveryDocument();
if (discoDoc.IsError) { if (discoDoc.IsError)
XException.ActionFailed.Throw (); {
XException.ActionFailed.Throw();
} }
// //
var response = await httpClient.IntrospectTokenAsync (new TokenIntrospectionRequest { var response = await httpClient.IntrospectTokenAsync(new TokenIntrospectionRequest
{
// //
Address = discoDoc.IntrospectionEndpoint, Address = discoDoc.IntrospectionEndpoint,
ClientId = identityConfiguration.ClientId, ClientId = identityConfiguration.ClientId,
ClientSecret = identityConfiguration.ClientSecret, ClientSecret = identityConfiguration.ClientSecret,
// //
Token = model.AccessToken Token = model.AccessToken
}); });
if (response.IsError) { if (response.IsError)
throw new Exception (response.Error); {
throw new Exception(response.Error);
} }
// //
return response; return response;
} catch {
throw XException.ActionFailed.ToException ();
} }
catch
{
throw XException.ActionFailed.ToException();
}
}
/// <summary>
/// Validate Specified Token Model ...
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public async Task<TokenIntrospectionResponse> Validate(XTokenResponse model)
{
//
// Validate Args ...
await validationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotEmpty(model.AccessToken)
.ValidateGroupAsync();
//
var httpClient = GetHttpClient();
//
TokenIntrospectionResponse response = null;
try
{
//
var discoDoc = await RequestDiscoveryDocument();
if (discoDoc.IsError)
{
XException.ActionFailed.Throw();
}
//
response = await httpClient.IntrospectTokenAsync(new TokenIntrospectionRequest
{
//
Address = discoDoc.IntrospectionEndpoint,
ClientId = identityConfiguration.ClientId,
ClientSecret = identityConfiguration.ClientSecret,
//
Token = model.AccessToken
});
}
catch
{ }
//
return response;
} }
/// <summary> /// <summary>
@@ -129,25 +196,26 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="model">User Login Required Info, an instance of <see>XLoginRequest</see></param> /// <param name="model">User Login Required Info, an instance of <see>XLoginRequest</see></param>
/// <returns>an instance of <see>XTokenResponse</see></returns> /// <returns>an instance of <see>XTokenResponse</see></returns>
public async Task<XTokenResponse> Authenticate (XLoginRequest model) { public async Task<XTokenResponse> Authenticate(XLoginRequest model)
{
// //
// Validate Args ... // Validate Args ...
validationProvider validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (model) .AddNotNull(model)
.AddNotEmpty ( .AddNotEmpty(
model.UserSelectBy, model.UserSelectBy,
model.Password model.Password
) )
.ValidateGroup (); .ValidateGroup();
// //
var client = GetRestClient (); var client = GetRestClient();
var request = GetRestRequet (XApiAccountEndpoint.Authenticate); var request = GetRestRequet(XApiAccountEndpoint.Authenticate);
request.AddJsonBody (model); request.AddJsonBody(model);
// //
var response = await RunRestRequest<XTokenResponse> ( var response = await RunRestRequest<XTokenResponse>(
client, client,
request, request,
XHttpMethod.POST XHttpMethod.POST
@@ -155,8 +223,9 @@ namespace xIdentityService.Providers {
// //
// Save Token ... // Save Token ...
if (!response.IsNull ()) { if (!response.IsNull())
await tokenProvider.AddOrUpdateToken (response); {
await tokenProvider.AddOrUpdateToken(response);
} }
// //
@@ -168,35 +237,37 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="model">User Login Required Info, an instance of <see>XLoginRequest</see></param> /// <param name="model">User Login Required Info, an instance of <see>XLoginRequest</see></param>
/// <returns>an instance of <see>XTokenResponse</see></returns> /// <returns>an instance of <see>XTokenResponse</see></returns>
public async Task<XLoginResponse> Login (XLoginRequest model) { public async Task<XLoginResponse> Login(XLoginRequest model)
{
// //
// Validate Args ... // Validate Args ...
validationProvider validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (model, model.Device) .AddNotNull(model, model.Device)
.AddNotEmpty ( .AddNotEmpty(
model.UserSelectBy, model.UserSelectBy,
model.Password model.Password
) )
.ValidateGroup (); .ValidateGroup();
// //
var client = GetRestClient (); var client = GetRestClient();
var request = GetRestRequet (XApiAccountEndpoint.Login); var request = GetRestRequet(XApiAccountEndpoint.Login);
request.AddJsonBody (model); request.AddJsonBody(model);
// //
var response = await RunRestRequest<XLoginResponse> ( var response = await RunRestRequest<XLoginResponse>(
client, client,
request, request,
XHttpMethod.POST XHttpMethod.POST
); );
// //
if (!response.IsNull ()) { if (!response.IsNull())
{
// //
var tokens = response.ToXTokenResponse (); var tokens = response.ToXTokenResponse();
await tokenProvider.AddOrUpdateToken (tokens); await tokenProvider.AddOrUpdateToken(tokens);
} }
// //
@@ -208,20 +279,22 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
/// <returns></returns> /// <returns></returns>
public async Task Logout (XTokenResponse model) { public async Task Logout(XTokenResponse model)
{
// //
await validationProvider await validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (model) .AddNotNull(model)
.AddNotEmpty (model.AccessToken) .AddNotEmpty(model.AccessToken)
.ValidateGroupAsync (); .ValidateGroupAsync();
// //
var isExists = await tokenProvider var isExists = await tokenProvider
.IsTokenExists (model.AccessToken); .IsTokenExists(model.AccessToken);
if (isExists) { if (isExists)
{
await tokenProvider await tokenProvider
.RemoveToken (model.AccessToken); .RemoveToken(model.AccessToken);
} }
} }
@@ -230,35 +303,37 @@ namespace xIdentityService.Providers {
/// </summary> /// </summary>
/// <param name="model">Authentication Tokens</param> /// <param name="model">Authentication Tokens</param>
/// <returns>an instance of <see>XTokenResponse</see></returns> /// <returns>an instance of <see>XTokenResponse</see></returns>
public async Task<XTokenResponse> RefreshTokens (XTokenResponse model) { public async Task<XTokenResponse> RefreshTokens(XTokenResponse model)
{
// //
// Validate Args ... // Validate Args ...
validationProvider validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (model) .AddNotNull(model)
.AddNotEmpty ( .AddNotEmpty(
model.AccessToken, model.AccessToken,
model.RefreshToken model.RefreshToken
) )
.ValidateGroup (); .ValidateGroup();
// //
var client = GetRestClient (model); var client = GetRestClient(model);
// //
var request = GetRestRequet ( var request = GetRestRequet(
XApiAccountEndpoint.RefreshTokens, XApiAccountEndpoint.RefreshTokens,
headers : model.ToHeaderDictionary ()); headers: model.ToHeaderDictionary());
request.AddJsonBody (model); request.AddJsonBody(model);
// //
var response = await RunRestRequest<XTokenResponse> ( var response = await RunRestRequest<XTokenResponse>(
client, client,
request, request,
XHttpMethod.POST XHttpMethod.POST
); );
if (!response.IsNull ()) { if (!response.IsNull())
await tokenProvider.UpdateToken (response); {
await tokenProvider.UpdateToken(response);
} }
// //
@@ -274,39 +349,40 @@ namespace xIdentityService.Providers {
/// <param name="tokens">Authentication Tokens</param> /// <param name="tokens">Authentication Tokens</param>
/// <param name="model">an instance of <see>XActionRequest</see> class which provider requirement for action</param> /// <param name="model">an instance of <see>XActionRequest</see> class which provider requirement for action</param>
/// <returns></returns> /// <returns></returns>
public async Task ChangePassword ( public async Task ChangePassword(
XTokenResponse tokens, XTokenResponse tokens,
XActionRequest model XActionRequest model
) { )
{
// //
// Validate Args ... // Validate Args ...
await validationProvider await validationProvider
.GroupValidationBuilder () .GroupValidationBuilder()
.AddNotNull (tokens, model) .AddNotNull(tokens, model)
.AddNotEmpty ( .AddNotEmpty(
model.Lang, model.Lang,
model.Password, model.Password,
model.NewPassword, model.NewPassword,
model.ReturnUrl) model.ReturnUrl)
.AddNotNull (model.Device) .AddNotNull(model.Device)
.ValidateGroupAsync (); .ValidateGroupAsync();
// //
// Validate User Select By Param ... // Validate User Select By Param ...
var userSelectByParam = GetUserSelectByParam ( var userSelectByParam = GetUserSelectByParam(
model, model,
forceNotNull : true, forceNotNull: true,
excludes : null); excludes: null);
// //
var client = GetRestClient (tokens); var client = GetRestClient(tokens);
var request = GetRestRequet ( var request = GetRestRequet(
XApiAccountEndpoint.ChangePassword, XApiAccountEndpoint.ChangePassword,
headers : tokens.ToHeaderDictionary ()); headers: tokens.ToHeaderDictionary());
request.AddJsonBody (model); request.AddJsonBody(model);
// //
var response = await RunRestRequest<Object> ( var response = await RunRestRequest<Object>(
client, client,
request, request,
XHttpMethod.POST XHttpMethod.POST
+203 -1
View File
@@ -20,7 +20,7 @@ namespace xIdentityService.Providers
/// Prepare API Based Device to Open Actions ... /// Prepare API Based Device to Open Actions ...
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public XDeviceDto GetDevice() public XDeviceDto GetDevice()
{ {
// //
var os = "XSaherElmOS"; var os = "XSaherElmOS";
@@ -171,6 +171,208 @@ namespace xIdentityService.Providers
} }
#endregion #endregion
//
#region GetApiKey ...
public async Task<Guid> GetApiKey(
XDeviceDto device,
string apiKey
)
{
//
// Validate Args ...
validationProvider.NotNull(device);
validationProvider.NotEmpty(apiKey);
//
// Prepare Open Action Model ...
var opaModel = new XOpenActionRequestDto
{
Device = device,
Payload = apiKey,
Action = XOpenActions.GetApiKey,
Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString()
};
if (!opaModel.Validate())
{
XException.InvalidArgs.Throw();
}
//
// Fill Checksum Filed ...
var token = opaModel.ToOpenActionToken();
opaModel.Checksum = token;
//
// Prepare Request ...
var opaJson = opaModel.ToJson();
var requestString = SecurityProvider.Encrypt(opaJson);
//
return await GetApiKey(
token: token,
request: requestString
);
}
public async Task<Guid> GetApiKey(
XOpenActionInnerDto dto
)
{
//
return await GetApiKey(
token: dto.Token,
request: dto.Payload
);
}
public async Task<Guid> GetApiKey(
string token,
string request
)
{
//
// Validate Args ...
validationProvider.NotEmpty(token);
validationProvider.NotEmpty(request);
//
// Retrieve and Validate Response ...
var response = await OpenGet(
token: token,
actionRequest: request
);
if (response.IsNull() ||
response.Token.IsNullOrEmpty() ||
response.Payload.IsNullOrEmpty()
)
{
XException.ActionFailed.Throw();
}
//
// Now we Have to Converts Repose Payload to Result Model ...
// Note that the respose Model's payload here is Decrypted and
// actually is Json Representation of Result Model ...
var requestModel = response.Payload.FromJSON<XOpenActionRequestDto>();
if (requestModel.IsNull())
{
XException.ActionFailed.Throw();
}
//
var resultString = SecurityProvider.Decrypt(requestModel.Payload);
var result = new Guid(resultString);
if (result.IsNull())
{
XException.NotFound.Throw();
}
//
return result;
}
#endregion
//
#region UseApiKey ...
public async Task<bool> UseApiKey(
XDeviceDto device,
XApiKeyUsageDto apiKeyUsage
)
{
//
// Validate Args ...
validationProvider.NotNull(device);
validationProvider.NotNull(apiKeyUsage);
//
// Prepare Open Action Model ...
var opaModel = new XOpenActionRequestDto
{
Device = device,
Payload = apiKeyUsage.ToJSON(),
Action = XOpenActions.UseApiKey,
Timestamp = DateTime.UtcNow.AddMinutes(5).ToTimestamp().ToString()
};
if (!opaModel.Validate())
{
XException.InvalidArgs.Throw();
}
//
// Fill Checksum Filed ...
var token = opaModel.ToOpenActionToken();
opaModel.Checksum = token;
//
// Prepare Request ...
var opaJson = opaModel.ToJson();
var requestString = SecurityProvider.Encrypt(opaJson);
//
return await UseApiKey(
token: token,
request: requestString
);
}
public async Task<bool> UseApiKey(
XOpenActionInnerDto dto
)
{
//
return await UseApiKey(
token: dto.Token,
request: dto.Payload
);
}
public async Task<bool> UseApiKey(
string token,
string request
)
{
//
// Validate Args ...
validationProvider.NotEmpty(token);
validationProvider.NotEmpty(request);
//
// Retrieve and Validate Response ...
var response = await OpenGet(
token: token,
actionRequest: request
);
if (response.IsNull() ||
response.Token.IsNullOrEmpty() ||
response.Payload.IsNullOrEmpty()
)
{
XException.ActionFailed.Throw();
}
//
// Now we Have to Converts Repose Payload to Result Model ...
// Note that the respose Model's payload here is Decrypted and
// actually is Json Representation of Result Model ...
var requestModel = response.Payload.FromJSON<XOpenActionRequestDto>();
if (requestModel.IsNull())
{
XException.ActionFailed.Throw();
}
//
var resultJson = SecurityProvider.Decrypt(requestModel.Payload).ToNormalString();
var result = resultJson.FromJSON<bool>();
if (result.IsNull())
{
XException.NotFound.Throw();
}
//
return result;
}
#endregion
// //
#region GetUserInfo ... #region GetUserInfo ...
public async Task<XOpenActionUserInfoDto> GetUserInfo( public async Task<XOpenActionUserInfoDto> GetUserInfo(
+96
View File
@@ -0,0 +1,96 @@
using System;
using xCommons.Extensions;
using xCommons.Configurations;
using xIdentityService.Constants;
using xIdentityService.Interfaces;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;
namespace xIdentityService.Providers
{
/// <summary>
/// Thread-safe local cache; IMemoryCache gives TTL,
/// ConcurrentDictionary gives key tracking for Clear() ...
/// </summary>
public class XAuthorizationCache : IXAuthorizationCache
{
private readonly TimeSpan ttl;
private readonly IMemoryCache cache;
private readonly ConcurrentDictionary<string, byte> keys = new();
private readonly XAppConfiguration appConfiguration;
public XAuthorizationCache(
IMemoryCache cache,
XAppConfiguration appConfiguration
)
{
//
this.cache = cache;
this.appConfiguration = appConfiguration;
ttl = TimeSpan.FromMinutes(appConfiguration.DefaultCacheTtlMinutes);
}
public bool TryGetPolicy(
string name,
out AuthorizationPolicy policy
)
{
//
policy = null;
//
var result =
!name.IsNullOrEmpty() &&
cache.TryGetValue(Key(name), out policy);
return result;
}
public void SetPolicy(
string name,
AuthorizationPolicy policy
)
{
//
if (name.IsNullOrEmpty() || policy.IsNull())
{
return;
}
//
cache.Set(Key(name), policy, ttl);
keys[Key(name)] = 0;
}
public void RemovePolicy(string name)
{
//
if (name.IsNullOrEmpty())
{
return;
}
//
cache.Remove(Key(name));
keys.TryRemove(Key(name), out _);
}
public void Clear()
{
//
foreach (var key in keys.Keys)
{
cache.Remove(key);
}
//
keys.Clear();
}
//
#region Private ...
private static string Key(string name) =>
XIdentityServiceConstants.PolicyCacheKeyPrefix + name.ToNormalString();
#endregion
}
}
+258
View File
@@ -0,0 +1,258 @@
using System;
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityService.Models;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xIdentityService.Extensions;
//
// TODO: Remove this to xIds ...
namespace xIdentityService.Providers
{
public partial class XAuthorizationProvider // : IXAuthorizationProvider
{
//
// private readonly IXRoleProvider roles;
// private readonly IXScopeProvider scopes;
// private readonly IXPolicyProvider policies;
// private readonly IXAuthorizationCache cache;
// private readonly IXRoleHierarchyResolver resolver;
// public XAuthorizationProvider(
// IXRoleProvider roles,
// IXScopeProvider scopes,
// IXPolicyProvider policies,
// IXAuthorizationCache cache,
// IXRoleHierarchyResolver resolver
// )
// {
// //
// this.roles = roles;
// this.cache = cache;
// this.scopes = scopes;
// this.policies = policies;
// this.resolver = resolver;
// }
// //
// #region Commons ...
// /// <summary>
// /// Clear Local Cache and Notify other Instances ...
// /// </summary>
// public async Task InvalidateAsync(string policyName = null)
// {
// //
// if (policyName.IsNullOrEmpty())
// {
// cache.Clear();
// }
// else
// {
// cache.RemovePolicy(policyName);
// }
// }
// #endregion
// //
// #region Private ...
// private async Task<XRoleDefinitionDto> FindRoleOrThrowAsync(
// string name,
// CancellationToken cancellationToken
// )
// {
// //
// if (name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var normalized = name.ToNormalString();
// var result = await roles.FindOneAsync(
// predicate: r => r.Name.ToLower() == normalized,
// cancellationToken: cancellationToken
// );
// if (result.IsNull())
// {
// XException.NotFound.Throw();
// }
// //
// return result;
// }
// private async Task<XScopeDefinitionDto> FindScopeOrThrowAsync(
// string name,
// CancellationToken cancellationToken
// )
// {
// //
// if (name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var normalized = name.ToNormalString();
// var result = await scopes.FindOneAsync(
// predicate: s => s.Name.ToLower() == normalized,
// cancellationToken: cancellationToken
// );
// if (result.IsNull())
// {
// XException.NotFound.Throw();
// }
// //
// return result;
// }
// private async Task<XPolicyDefinitionDto> FindPolicyOrThrowAsync(
// string name,
// CancellationToken cancellationToken
// )
// {
// //
// if (name.IsNullOrEmpty())
// {
// XException.InvalidArgs.Throw();
// }
// //
// var normalized = name.ToNormalString();
// var result = await policies.FindOneAsync(
// predicate: p => p.Name.ToLower() == normalized,
// cancellationToken: cancellationToken
// );
// if (result.IsNull())
// {
// XException.NotFound.Throw();
// }
// //
// return result;
// }
// private async Task ValidateReferencesAsync(
// XPolicyDefinitionDto item,
// CancellationToken cancellationToken
// )
// {
// //
// // Defensive guard ...
// if (item.IsNull())
// {
// XException.InvalidArgs.Throw();
// }
// //
// // The DTO stores RequiredRoles / RequiredScopes as CSV strings.
// // Parse them into collections ONCE (ParseListString NREs on a null
// // string, so guard first) ...
// //
// var requiredRoles = item.RequiredRoles.IsNullOrEmpty()
// ? []
// : item.RequiredRoles.ParseListString<string>().ToList();
// //
// var requiredScopes = item.RequiredScopes.IsNullOrEmpty()
// ? []
// : item.RequiredScopes.ParseListString<string>().ToList();
// //
// // Referenced Roles must exist ...
// if (requiredRoles.HasChild())
// {
// //
// var existingRoles = new HashSet<string>(
// (await roles.GetAllAsync(cancellationToken: cancellationToken))
// .Select(r => r.Name.ToNormalString()),
// StringComparer.OrdinalIgnoreCase
// );
// if (requiredRoles.Any(r => !existingRoles.Contains(r.ToNormalString())))
// {
// XException.NotFound.Throw();
// }
// }
// //
// // Referenced Scopes must exist ...
// if (requiredScopes.HasChild())
// {
// //
// var existingScopes = new HashSet<string>(
// (await scopes.GetAllAsync(cancellationToken: cancellationToken))
// .Select(s => s.Name.ToNormalString()),
// StringComparer.OrdinalIgnoreCase
// );
// if (requiredScopes.Any(s => !existingScopes.Contains(s.ToNormalString())))
// {
// XException.NotFound.Throw();
// }
// }
// }
// private async Task<XEffectiveAuthorizationDto> ToDtoWithEffectiveRolesAsync(
// XPolicyDefinitionDto item,
// CancellationToken cancellationToken = default
// )
// {
// //
// // Null / nameless guard ...
// if (item.IsNull() || item.Name.IsNullOrEmpty())
// {
// return null;
// }
// //
// // Parse the DTO's CSV-string RequiredRoles. ParseListString NREs on a
// // null string, so guard first; the resolver itself is null-safe on an
// // empty explicitRoles set ...
// var explicitRoles = item.RequiredRoles.IsNullOrEmpty()
// ? null
// : item.RequiredRoles.ParseListString<string>();
// //
// // Resolve the effective role set
// // (explicit RequiredRoles U roles by MinRoleWeight U parent chain) ...
// var effectiveRoles = await resolver.ResolveEffectiveRolesAsync(
// explicitRoles: explicitRoles,
// minRoleWeight: item.MinRoleWeight,
// cancellationToken: cancellationToken
// );
// //
// // Project onto XEffectiveAuthorizationDto - the ONLY DTO that carries
// // EffectiveRoles / EffectiveScopes / EffectiveClaims. Each CSV / JSON
// // field is null-guarded here (the shared ToEffectiveAuthorization
// // extension calls ParseListString on RequiredScopes without a null
// // guard, so the projection is built inline to stay null-safe) ...
// var result = new XEffectiveAuthorizationDto
// {
// PolicyName = item.Name,
// RequireEnabledUser = item.RequireEnabledUser,
// RequireAuthenticatedUser = item.RequireAuthenticatedUser,
// EffectiveClaims = item.RequiredClaims.ToRequiredClaims(),
// EffectiveScopes = item.RequiredScopes.IsNullOrEmpty()
// ? new HashSet<string>(StringComparer.OrdinalIgnoreCase)
// : new HashSet<string>(
// item.RequiredScopes.ParseListString<string>(),
// StringComparer.OrdinalIgnoreCase
// ),
// EffectiveRoles = effectiveRoles.HasChild()
// ? new HashSet<string>(effectiveRoles, StringComparer.OrdinalIgnoreCase)
// : new HashSet<string>(StringComparer.OrdinalIgnoreCase),
// };
// //
// return result;
// }
// #endregion
}
}
+459
View File
@@ -0,0 +1,459 @@
using RestSharp;
using System.Linq;
using System.Threading;
using xCommons.Providers;
using xCommons.Constants;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xHttpService.Constants;
using xHttpService.Providers;
using xIdentityModels.Models;
using xIdentityService.Models;
using xIdentityService.Constants;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using xHttpService.Configurations;
using Microsoft.Extensions.Logging;
using xIdentityService.Configuration;
namespace xIdentityService.Providers
{
public partial class XIdentityHttpProvider : XHttpProvider, IXIdentityHttpProvider
{
private readonly IXTokenProvider tokenProvider;
private readonly IXIdentityProvider identityProvider;
private readonly ILogger<XIdentityHttpProvider> logger;
private readonly XValidationProvider validationProvider;
private readonly XIdentityServiceConfiguration identityConfiguration;
public XIdentityHttpProvider(
IXTokenProvider tokenProvider,
IXIdentityProvider identityProvider,
ILogger<XIdentityHttpProvider> logger,
XValidationProvider validationProvider,
XHttpServiceConfiguration configuration,
XIdentityServiceConfiguration identityConfiguration
) : base(
logger,
configuration
)
{
//
this.logger = logger;
this.tokenProvider = tokenProvider;
this.identityProvider = identityProvider;
this.validationProvider = validationProvider;
this.identityConfiguration = identityConfiguration;
}
/// <summary>
/// Get an Instance of RestRequest ...
/// </summary>
/// <param name="endpoint"></param>
/// <param name="addXPoweredValue"></param>
/// <param name="params"></param>
/// <param name="headers"></param>
/// <param name="queryStrings"></param>
/// <returns></returns>
public RestRequest GetRestRequest(
string endpoint,
bool addXPoweredValue = true,
IDictionary<string, string> @params = null,
IDictionary<string, string> headers = null,
IDictionary<string, string> queryStrings = null
)
{
//
var url = endpoint;
//
// Add Route Payloads ...
if (!@params.IsNull() && @params.Count > 0)
{
//
var enumerator = @params.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
//
url = url.Replace(item.Key, item.Value.ToUrlEncoded());
}
}
//
// Add Query Strings ...
if (!queryStrings.IsNull() && queryStrings.Count > 0)
{
//
url = $"{url}?";
var enumerator = queryStrings.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
//
url += $"{item.Key}={item.Value.ToUrlEncoded()}&";
}
//
// remove lates & ...
if (url.EndsWith("&"))
{
url = url.Substring(0, url.Length - 1);
}
}
//
// Create request ...
var request = new RestRequest(url, DataFormat.Json);
//
if (addXPoweredValue)
{
request.AddHeader(XAuthorization.XPoweredBy, identityConfiguration.XPoweredValue);
}
//
// Add Headers to request ...
if (!headers.IsNull() && headers.Count > 0)
{
//
var enumerator = headers.GetEnumerator();
while (enumerator.MoveNext())
{
//
var item = enumerator.Current;
request.AddHeader(item.Key, item.Value);
}
}
//
return request;
}
/// <summary>
/// Handle Call Specific Request and retrieve Response
/// </summary>
/// <param name="client"></param>
/// <param name="request"></param>
/// <param name="method"></param>
/// <param name="supportRefreshingTokens"></param>
/// <param name="cancellationToken"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public async Task<T> RunRestRequest<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
)
{
//
var response = await Task.Run(async () =>
{
//
IRestResponse resp = null;
//
// Call Endpoint Service using Specified Method ...
switch (method)
{
//
// Get ...
case XHttpMethod.GET:
resp = client.Get(request);
break;
//
// Put ...
case XHttpMethod.PUT:
resp = client.Put(request);
break;
//
// Post ...
case XHttpMethod.POST:
resp = client.Post(request);
break;
//
// Delete ...
case XHttpMethod.DELETE:
resp = client.Delete(request);
break;
}
//
if (!resp.IsSuccessful)
{
//
// Log Exception ...
logger.LogError($"Error: {resp.ErrorMessage}");
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
if (!resp.ErrorMessage.IsNullOrEmpty() &&
resp.ErrorMessage.Contains("timed out"))
{
XException.Timeout.Throw();
}
//
// Refresh Tokens or Issue Correct Exception ...
if (supportRefreshingTokens &&
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//
var isRefreshed = request.Parameters.Any(rp =>
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
rp.Value.ToString().ToNormalString() == true.ToJSON());
//
logger.LogInformation($"isRefreshed: {isRefreshed}");
//
// Get Access Token ...
XTokenResponse tokens = null;
var accessToken = request.Parameters.FirstOrDefault(rp =>
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
if (!accessToken.IsNullOrEmpty())
{
//
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
//
if (!accessToken.IsNullOrEmpty())
{
tokens = await tokenProvider.RetrieveToken(accessToken);
}
}
//
// Refresh Token and then re do request ...
if (!isRefreshed &&
!accessToken.IsNullOrEmpty() &&
!tokens.IsNull() &&
tokens.IsRefreshable())
{
//
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
//
// Refreshe Tokens ...
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
//
// Renew Rest Client with Refreshed Tokens ...
var timeout = client.Timeout;
client = GetRestClient(
tokens: refreshedTokens,
baseUrl: client.BaseUrl.ToString()
);
client.Timeout = Timeout.Infinite;
//
// Do Request Again using renew Client ...
return await RunRestRequest<T>(
client: client,
request: request,
method: method);
}
}
//
var ex = resp.Content.ToXError();
if (!ex.IsNull())
{
throw ex.ToException();
}
//
// UnAuthorized ...
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
XException.NotAuthorized.Throw();
}
//
// NotFound ...
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
{
XException.NotFound.Throw();
}
//
XException.ActionFailed.Throw();
}
//
var result = resp.Content.FromJSON<T>();
return result;
}, cancellationToken);
//
return response;
}
public async Task<XBaseRestResponse<T>> RunRestRequestByResponse<T>(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
)
{
//
var response = await Task.Run(async () =>
{
//
IRestResponse resp = null;
//
// Call Endpoint Service using Specified Method ...
switch (method)
{
//
// Get ...
case XHttpMethod.GET:
resp = client.Get(request);
break;
//
// Put ...
case XHttpMethod.PUT:
resp = client.Put(request);
break;
//
// Post ...
case XHttpMethod.POST:
resp = client.Post(request);
break;
//
// Delete ...
case XHttpMethod.DELETE:
resp = client.Delete(request);
break;
}
//
if (!resp.IsSuccessful)
{
//
// Log Exception ...
logger.LogError($"Error: {resp.ErrorMessage}");
logger.LogError($"Exception: {resp.ErrorException.ToJSON()}");
if (!resp.ErrorMessage.IsNullOrEmpty() &&
resp.ErrorMessage.Contains("timed out"))
{
XException.Timeout.Throw();
}
//
// Refresh Tokens or Issue Correct Exception ...
if (supportRefreshingTokens &&
resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
//
var isRefreshed = request.Parameters.Any(rp =>
rp.Name == XParam.XIsRefreshed.GetStringValue() &&
rp.Value.ToString().ToNormalString() == true.ToJSON());
//
logger.LogInformation($"isRefreshed: {isRefreshed}");
//
// Get Access Token ...
XTokenResponse tokens = null;
var accessToken = request.Parameters.FirstOrDefault(rp =>
rp.Name.ToNormalString() == XAuthorization.Header.ToNormalString()).Value.ToString();
if (!accessToken.IsNullOrEmpty())
{
//
accessToken = accessToken.Replace(XAuthorization.TokenIdentifier, "");
//
if (!accessToken.IsNullOrEmpty())
{
tokens = await tokenProvider.RetrieveToken(accessToken);
}
}
//
// Refresh Token and then re do request ...
if (!isRefreshed &&
!accessToken.IsNullOrEmpty() &&
!tokens.IsNull() &&
tokens.IsRefreshable())
{
//
request.AddHeader(XParam.XIsRefreshed.GetStringValue(), true.ToJSON());
//
// Refreshe Tokens ...
var refreshedTokens = await identityProvider.RefreshTokens(tokens);
//
// Renew Rest Client with Refreshed Tokens ...
var timeout = client.Timeout;
client = GetRestClient(
tokens: refreshedTokens,
baseUrl: client.BaseUrl.ToString()
);
client.Timeout = Timeout.Infinite;
//
// Do Request Again using renew Client ...
return await RunRestRequestByResponse<T>(
client: client,
request: request,
method: method
);
}
}
//
var ex = resp.Content.ToXError();
if (!ex.IsNull())
{
throw ex.ToException();
}
//
// UnAuthorized ...
if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
XException.NotAuthorized.Throw();
}
//
// NotFound ...
if (resp.StatusCode == System.Net.HttpStatusCode.NotFound)
{
XException.NotFound.Throw();
}
//
XException.ActionFailed.Throw();
}
//
var result = new XBaseRestResponse<T>
{
Response = resp,
Model = resp.Content.FromJSON<T>()
};
//
return result;
}, cancellationToken);
//
return response;
}
}
}
+92
View File
@@ -0,0 +1,92 @@
using System;
using System.Linq;
using xModels.Dtos;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityService.Extensions;
using xIdentityService.Interfaces;
using System.Collections.Concurrent;
namespace xIdentityService.Providers
{
public class XPersonService : IXPersonService
{
//
private readonly IXIdentityProvider identityProvider;
private readonly ConcurrentDictionary<string, XPersonDto> persons = new ConcurrentDictionary<string, XPersonDto>();
public XPersonService(
IXIdentityProvider identityProvider
)
{
this.identityProvider = identityProvider;
}
public async Task<XPersonDto> GetPerson(string userId)
{
//
// Validate ...
if (userId.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
XPersonDto result = null;
//
// if Persons has Child, Check it ...
if (persons.HasChild())
{
//
var personEntry = persons
.FirstOrDefault(p => p.Key.Equals(userId, StringComparison.InvariantCultureIgnoreCase));
if (!personEntry.IsNull())
{
result = personEntry.Value;
}
}
//
// Check if Person not Exists ...
if (result.IsNullOrDefault())
{
//
// Prepare Device ...
var device = identityProvider.GetDevice();
//
// Retrieve User Info in OpenAction ...
var userInfo = await identityProvider
.GetUserInfo(
device: device,
userSelectByParam: userId
);
//
// Converts to Person Dto ...
result = userInfo.ToXPersonDto();
//
// Update Persons Dictionary ...
if (!result.IsNullOrDefault())
{
persons[userId] = result;
}
}
//
Cleanup();
//
return result;
}
public void Cleanup()
{
//
// TODO: Implement Cleanup Pesons ...
}
}
}
+140
View File
@@ -0,0 +1,140 @@
using System;
using System.Linq;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.EntityFrameworkCore.Internal;
namespace xIdentityService.Providers
{
public class XPolicyHandler : IXPolicyHandler
{
private readonly static Dictionary<string, IEnumerable<string>> policies = [];
/// <summary>
/// Add Specified Role ...
/// </summary>
/// <param name="policy"></param>
/// <param name="requiredRoles"></param>
/// <returns></returns>
public bool AddPolicy(
string policy,
IEnumerable<string> requiredRoles
)
{
//
// Validate ...
if (policy.IsNullOrEmpty() ||
!requiredRoles.HasChild()
)
{
XException.InvalidArgs.Throw();
}
//
var result = !HasPolicy(policy);
if (!result)
{
return result;
}
//
policies[policy] = requiredRoles;
//
return result;
}
/// <summary>
/// Check Specified Role Exists or not ...
/// </summary>
/// <param name="policy"></param>
/// <returns></returns>
public bool HasPolicy(string policy)
{
//
var result =
policies.HasChild() &&
!policy.IsNullOrEmpty() &&
policies.Keys.Any(p => p
.Equals(policy, StringComparison.InvariantCultureIgnoreCase));
//
return result;
}
/// <summary>
/// Remove Specified Role ...
/// </summary>
/// <param name="policy"></param>
/// <returns></returns>
public bool RemovePolicy(string policy)
{
//
// Validate ...
if (policy.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
var result = HasPolicy(policy);
if (!result)
{
return result;
}
//
result = policies.Remove(policy);
//
return result;
}
/// <summary>
/// Check Specified Policy passed or not ...
/// </summary>
/// <param name="policy"></param>
/// <param name="roles"></param>
/// <returns></returns>
public bool IsPolicyPassed(
string policy,
IEnumerable<string> roles
)
{
//
// Validate ...
if (!roles.HasChild() ||
policy.IsNullOrEmpty())
{
XException.InvalidArgs.Throw();
}
//
// Normalize ...
policy = policy.ToNormalString();
//
var result = HasPolicy(policy);
if (!result)
{
return result;
}
//
var requiredRoles = policies[policy];
result =
requiredRoles.HasChild() &&
roles.All(r => requiredRoles
.Any(rq => r.Equals(rq, StringComparison.InvariantCultureIgnoreCase)));
//
return result;
}
//
#region Private ...
#endregion
}
}
+100
View File
@@ -0,0 +1,100 @@
using System;
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using System.Threading.Tasks;
using System.Collections.Generic;
using xIdentityService.Interfaces;
namespace xIdentityService.Providers
{
public class XRoleHierarchyResolver : IXRoleHierarchyResolver
{
private readonly IXRoleProvider provider;
public XRoleHierarchyResolver(
IXRoleProvider provider
)
{
this.provider = provider;
}
public async Task<IEnumerable<string>> GetRolesByMinWeightAsync(
int minWeight,
CancellationToken cancellationToken = default
)
{
//
var roles = await provider.FindManyAsync(
predicate: r => r.IsEnabled && r.Weight >= minWeight,
orderBuilder: q => q.OrderBy(r => r.Weight),
cancellationToken: cancellationToken
);
//
var result = roles
.Select(r => r.Name.ToNormalString())
.Distinct()
.ToList();
return result;
}
public async Task<IEnumerable<string>> ResolveEffectiveRolesAsync(
IEnumerable<string> explicitRoles,
int? minRoleWeight,
CancellationToken cancellationToken = default
)
{
//
var result = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
//
// Explicit Roles ...
if (explicitRoles.HasChild())
{
//
foreach (var role in explicitRoles)
{
result.Add(role.ToNormalString());
}
}
//
// Roles by Weight ...
if (minRoleWeight.HasValue)
{
//
var byWeight = await GetRolesByMinWeightAsync(
minRoleWeight.Value,
cancellationToken
);
foreach (var role in byWeight)
{
result.Add(role);
}
}
//
// Parent Chain: any Role whose ParentRoleName is in result inherits it ...
var all = await provider.GetAllAsync(cancellationToken: cancellationToken);
bool changed;
do
{
//
changed = false;
foreach (var role in all.Where(r => r.IsEnabled && !r.ParentRoleName.IsNullOrEmpty()))
{
//
if (result.Contains(role.ParentRoleName) &&
result.Add(role.Name.ToNormalString()))
{
changed = true;
}
}
} while (changed);
//
return [.. result];
}
}
}
+2 -6
View File
@@ -20,8 +20,7 @@
<!-- Icon Handling --> <!-- Icon Handling -->
<ItemGroup> <ItemGroup>
<None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true" <None Include="../../Documents/Resources/Images/favicon.png" Link="icon.png" Pack="true" PackagePath="\icon.png" />
PackagePath="\icon.png" />
</ItemGroup> </ItemGroup>
<!-- Local Modules --> <!-- Local Modules -->
@@ -32,15 +31,12 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="../xDataService/xDataService.csproj" /> <ProjectReference Include="../xDataService/xDataService.csproj" />
<ProjectReference Include="../xHttpService/xHttpService.csproj" /> <ProjectReference Include="../xHttpService/xHttpService.csproj" />
<!-- <PackageReference Include="xDashboard.xDataService" Version="1.0.0" /> -->
<!-- <PackageReference Include="xDashboard.xHttpService" Version="1.0.0" /> -->
</ItemGroup> </ItemGroup>
<!-- Dependencies --> <!-- Dependencies -->
<ItemGroup> <ItemGroup>
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection"
Version="4.0.0-preview.6" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.Abstractions" Version="2.2.0" />
<PackageReference Include="IdentityModel.AspNetCore.OAuth2Introspection" Version="4.0.0-preview.6" />
</ItemGroup> </ItemGroup>
<!-- For XML Documentation Support --> <!-- For XML Documentation Support -->