### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Attributes\XApiKeyAccessAttribute.cs
using System;
using System.Threading;
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.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
namespace xIdentityService.Attributes
{
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Method,
AllowMultiple = false,
Inherited = true
)]
public class XApiKeyAccessAttribute : AuthorizeAttribute, IAuthorizationFilter
{
///
/// Optional allowed scopes. If empty, no scope enforcement.
///
public XApiKeyScope[] Scopes { get; set; }
public XApiKeyAccessAttribute(
XApiKeyScope[] scopes = null
)
{
//
if (!scopes.HasChild())
{
scopes = [XApiKeyScope.Read];
}
//
Scopes = scopes;
}
///
/// Authorization Filtering ...
///
///
public void OnAuthorization(AuthorizationFilterContext context)
{
Task.FromResult(OnAuthorizationAsync(context));
}
///
/// Handle Authorization Filtering Using Tasks ...
///
///
///
///
private async Task OnAuthorizationAsync(
AuthorizationFilterContext context,
CancellationToken cancellationToken = default
)
{
//
// Access HttpContext ...
var http = context.HttpContext;
var error = XException.NotAuthorized.ToXError();
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
//
try
{
//
// Obtain the endpoint currently being executed
var endpointFeature = http.Features.Get();
var endpoint = endpointFeature?.Endpoint;
if (endpoint.IsNull() ||
endpointFeature.IsNull()
)
{
//
error.Message = "Endpoint not Accessible ...";
context.Result = new UnauthorizedObjectResult(error);
return;
}
//
// Retrieve Identity Provider Service from DI ...
var identityService = http.RequestServices
.GetService();
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);
}
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Configuration\XIdentityServiceConfiguration.cs
using xIdentityService.Constants;
namespace xIdentityService.Configuration {
public partial class XIdentityServiceConfiguration {
public string Authority { get; set; }
public string ApiName { get; set; }
public string ApiSecret { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string XPoweredValue { get; set; }
public XTokenType TokenType { get; set; }
public string XRevisionSecretKey { get; set; }
public int DefaultClientTimeout { get; set; } = 360;
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Configuration\XProxyConfiguration.cs
using xModels.Base;
using System.Collections.Generic;
namespace xIdentityService.Configuration {
///
/// XProxy Middleware Configuration ...
///
public class XProxyConfiguration {
///
/// Proxy Host Address for Clients Which Use XProxy Server ...
///
///
public string Host { get; set; }
///
/// if EnableXPoweredByAthorization property setted to true, this property determines
/// the header must be this value ...
///
///
public string XPoweredValue { get; set; }
///
/// Determines Proxy Http Handler Check SSL or not ...
///
///
public bool DisableSSLCheck { get; set; }
///
/// Determines Http Client Handler Allow Auto Redirect or not ...
///
///
public bool AllowAutoRedirect { get; set; }
///
/// Determines Proxy Server Log Received Requests or not ...
///
///
public bool EnableLogging { get; set; }
///
/// DefineRoutes for Handling ...
///
///
public HashSet Routes { get; set; }
}
///
/// Describe a Proxy Route ...
///
public class XProxyRouteDescriptor : XBaseDescriptor {
///
/// Determines which route can handled for Proxyfing ...
///
///
public string Route { get; set; }
///
/// Determines Proxy Server Handle Athorization or not ...
///
///
public bool EnableAuthorization { get; set; }
///
/// Determines Which Scopes allowed to this route if authorizations enabled ...
///
///
public HashSet AllowedScopes { get; set; }
///
/// Determines Which Roles allowed to this route if authorizations enabled ...
///
///
public HashSet AllowedRoles { get; set; }
///
/// Determines XProxy Can Check XPowered By Authorization or not ...
///
///
public bool EnableXPoweredByAthorization { get; set; }
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\ConfigurationNodeNames.cs
namespace xIdentityService.Constants {
public partial struct ConfigurationNodeNames {
public const string XPROXY_CONFIGURATION_NODE_NAME = "ProxyConfiguration";
public const string IDENTITY_SERVICE_NODE_NAME = "IdentityServiceConfiguration";
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XApiAccountEndpoint.cs
using xExceptions.Attributes;
namespace xIdentityService.Constants
{
public enum XApiAccountEndpoint
{
//
#region Authentication ...
[StringValue("Account/DiscoveryDocument")]
DiscoveryDocument,
[StringValue("Account/RequestScopeAccessToken")]
RequestScopeAccessToken,
[StringValue("Account/Authenticate")]
Authenticate,
[StringValue("Account/Login")]
Login,
[StringValue("Account/RefreshTokens")]
RefreshTokens,
[StringValue("Account/ChangePassword")]
ChangePassword,
[StringValue("Account/ResetPassword")]
ResetPassword,
#endregion
//
#region Proile ...
[StringValue("Account/Profile/{ids}/GetNames")]
GetNames,
[StringValue("Account/Profile/GetNameIds")]
GetNameIds,
[StringValue("Account/Profile/{userSelectByParam}")]
GetProfile,
[StringValue("Account/Profile/Query")]
QueryProfiles,
[StringValue("Account/Profile/Avatars/Query/{userSelectByParam}")]
QueryAvatars,
[StringValue("Account/Profile/Update/{userSelectByParam}")]
UpdateProfile,
[StringValue("Account/Profile/{userSelectByParam}")]
FullUpdateProfile,
[StringValue("Account/Profile/Avatar")]
AddAvatar,
[StringValue("Account/Profile/Avatars")]
AddAvatars,
[StringValue("Account/Profile/Avatars/{ids}")]
RemoveAvatars,
[StringValue("Account/Profile/Avatars/{id}/Set")]
SetAvatar,
#endregion
//
#region Search ...
[StringValue("Account/OpenToSearch/Query")]
QueryOpenToSearchProfiles,
#endregion
//
#region Registration ...
[StringValue("Account/CanRegisterUserName/{userName}")]
CanRegisterUserName,
[StringValue("Account/CanRegisterMobileNumber/{mobileNumber}")]
CanRegisterMobileNumber,
[StringValue("Account/CanRegisterEmail/{email}")]
CanRegisterEmail,
[StringValue("Account/IsConfirmedEmail")]
IsConfirmedEmail,
[StringValue("Account/IsConfirmedMobile")]
IsConfirmedMobile,
[StringValue("Account/ConfirmRegistration")]
ConfirmRegistration,
[StringValue("Account/ConfirmMobileNumber")]
ConfirmMobileNumber,
[StringValue("Account/ConfirmEmailAddress")]
ConfirmEmailAddress,
[StringValue("Account/RequestConfirmMobile")]
RequestConfirmMobile,
[StringValue("Account/RequestConfirmEmail")]
RequestConfirmEmail,
[StringValue("Account/RequestResetPassword")]
RequestResetPassword,
[StringValue("Account/RequestConfirmRegistration")]
RequestConfirmRegistration,
[StringValue("Account/InviteUser")]
InviteUser,
[StringValue("Account/RequestRegistration")]
RequestRegistration,
[StringValue("Account/AddAccountInfo")]
AddAccountInfo,
[StringValue("Account/AttachProfileImage")]
AttachProfileImage,
[StringValue("Account/FinishRegistration")]
FinishRegistration,
#endregion
//
#region Friendship ...
[StringValue("Account/Friendship/{destUser}/Follow")]
Follow,
[StringValue("Account/Friendship/{destUser}/Cancel")]
Cancel,
[StringValue("Account/Friendship/{destUser}/UnFollowFollower")]
UnFollowFollower,
[StringValue("Account/Friendship/{destUser}/UnFollowFollowing")]
UnFollowFollowing,
[StringValue("Account/Friendship/{destUser}/Block")]
Block,
[StringValue("Account/Friendship/{destUser}/UnBlock")]
UnBlock,
[StringValue("Account/Friendship/{destUser}/AcceptRequest")]
AcceptRequest,
[StringValue("Account/Friendship/{destUser}/RejectRequest")]
RejectRequest,
[StringValue("Account/Friendship/{destUser}/FriendshipInfo")]
FriendshipInfo,
[StringValue("Account/Friendship/{destUser}/IsFollower")]
IsFollower,
[StringValue("Account/Friendship/{destUser}/FollowerState")]
FollowerState,
[StringValue("Account/Friendship/{destUser}/Follower")]
Follower,
[StringValue("Account/Friendship/Followers")]
Followers,
[StringValue("Account/Friendship/AllFollowers")]
AllFollowers,
[StringValue("Account/Friendship/FollowersList")]
FollowersList,
[StringValue("Account/Friendship/QueryFollowers")]
QueryFollowers,
[StringValue("Account/Friendship/{destUser}/IsFollowing")]
IsFollowing,
[StringValue("Account/Friendship/{destUser}/FollowingState")]
FollowingState,
[StringValue("Account/Friendship/{destUser}/Following")]
Following,
[StringValue("Account/Friendship/Followings")]
Followings,
[StringValue("Account/Friendship/AllFollowings")]
AllFollowings,
[StringValue("Account/Friendship/FollowingsList")]
FollowingsList,
[StringValue("Account/Friendship/QueryFollowings")]
QueryFollowings,
#endregion
//
#region Admin ...
[StringValue("Account/Ban")]
Ban,
[StringValue("Account/UnBan")]
UnBan,
[StringValue("Account/IsBanned/{userSelectByParam}")]
IsBanned,
#endregion
//
#region Open Actions ...
[StringValue("Account/Open")]
Open,
#endregion
//
#region Applications ...
//
#region Application ...
[StringValue("Applications")]
CreateApplication,
[StringValue("Applications/{id}")]
UpdateApplication,
[StringValue("Applications/{id}")]
RemoveApplication,
[StringValue("Applications/{id}")]
GetApplication,
[StringValue("Applications")]
GetAllApplications,
[StringValue("Applications/Query")]
QueryApplications,
#endregion
//
#region ApiKey ...
[StringValue("Applications/ApiKeys/{id}")]
GetApiKey,
[StringValue("Applications/ApiKeys/{id}")]
RemoveApiKey,
[StringValue("Applications/ApiKeys/{id}")]
UpdateApiKey,
[StringValue("Applications/ApiKeys")]
GetAllApiKeys,
[StringValue("Applications/ApiKeys/Query")]
QueryApiKeys,
#endregion
//
#region ApiKeyUsage ...
[StringValue("Applications/ApiKeys/Usages")]
AddApiKeyUsage,
[StringValue("Applications/ApiKeys/Usages/{id}")]
GetApiKeyUsage,
[StringValue("Applications/ApiKeys/Usages/{id}")]
RemoveApiKeyUsage,
[StringValue("Applications/ApiKeys/Usages/{id}")]
UpdateApiKeyUsage,
[StringValue("Applications/Usages")]
GetAllApiKeyUsages,
[StringValue("Applications/Usages/Query")]
QueryApiKeyUsages,
#endregion
//
#region Custom ...
[StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Show")]
ShowApiKey,
[StringValue("Applications/{applicationId}/ApiKeys/Create")]
CreateApiKey,
[StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")]
RemoveApiKeyCustom,
[StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}")]
RotateApiKey,
[StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Revoke")]
RevokeApiKey,
[StringValue("Applications/{applicationId}/ApiKeys")]
GetApiKeys,
[StringValue("Applications/{applicationId}/ApiKeys/{apiKeyId}/Usages")]
GetApiKeyUsages,
[StringValue("Applications/ApiKeys/Validate")]
ValidateApiKey,
#endregion
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XAuthenticationScheme.cs
using xExceptions.Attributes;
namespace xIdentityService.Constants {
public enum XAuthenticationScheme {
[StringValue ("token")]
XToken,
[StringValue ("introspection")]
XIntrospection,
[StringValue("XApiKey")]
XApiKey,
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XHeader.cs
using xExceptions.Attributes;
namespace xIdentityService.Constants
{
///
/// All Available Headers ...
///
public enum XHeader
{
///
/// Hub Connection ID Header Keys ...
///
[StringValue("requestID")]
ConnectionId,
///
/// Api Key Header Key ...
///
[StringValue("X-Api-Key")]
ApiKey,
///
/// Checksum Digest Header Key ...
///
[StringValue("X-Check-Sum")]
ChecksumDigest,
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XIdentityServiceConstants.cs
namespace xIdentityService.Constants
{
public struct XIdentityServiceConstants
{
public const string PolicyCacheKeyPrefix = "XAuth:Cache";
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XParam.cs
using xExceptions.Attributes;
namespace xIdentityService.Constants {
public enum XParam {
[StringValue ("Content-Type")]
XContentType,
[StringValue ("{boundary}")]
XBoundary,
[StringValue ("{userSelectByParam}")]
XUserSelectByParam,
[StringValue ("{destUser}")]
XDestUser,
[StringValue ("{id}")]
XId,
[StringValue ("{ids}")]
XIds,
[StringValue ("Origin")]
XOrigin,
[StringValue ("{userName}")]
XUserName,
[StringValue ("{mobileNumber}")]
XMobileNumber,
[StringValue ("{email}")]
XEmail,
[StringValue ("role")]
XRole,
[StringValue ("forceRole")]
XForceRole,
[StringValue ("IsRefreshed")]
XIsRefreshed,
[StringValue ("file")]
XFile,
[StringValue ("files")]
XFiles,
[StringValue ("actionToken")]
XActionToken,
[StringValue ("request")]
XRequest,
[StringValue ("scope")]
XScope,
[StringValue("{apiKeyId}")]
XApiKeyId,
[StringValue("{applicationId}")]
XApplicationId,
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XProxyConstants.cs
namespace xIdentityService.Constants {
public struct XProxyConstants {
public const string XPROXY_HTTP_CLIENT = "XProxyHttpClient";
public const string XPROXY_FORWARD_HEADER = "xForwardHeader";
public const string XPROXY_ACCEPTED_HEADERS = "xAcceptedHeaders";
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XResponseContentTypes.cs
namespace xIdentityService.Constants {
public struct XResponseContentTypes {
public const string HTML = "text/html";
public const string JSON = "application/json";
public const string JavaScript = "text/javascript";
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Constants\XTokenType.cs
namespace xIdentityService.Constants {
public enum XTokenType {
//
// Summary:
// Self-contained Json Web Token
Jwt,
//
// Summary:
// Reference token
Reference
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseAccountController.cs
using System;
using xModels.Dtos;
using xCommons.Providers;
using xCommons.Attributes;
using xCommons.Extensions;
using xIdentityModels.Dtos;
using IdentityModel.Client;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using Microsoft.AspNetCore.Http;
using xIdentityModels.Extensions;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Controllers
{
[AllowAnonymous]
[RequireXPowered(true)]
public abstract class XBaseAccountController : XBaseIdentityController
{
protected XBaseAccountController(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{ }
//
#region Authentication Actions ...
///
/// Retrieve OAuth Discovery Document
///
/// an instance of DiscoveryDocumentResponse
[AllowAnonymous]
[RequireXPowered]
[HttpGet("DiscoveryDocument")]
public virtual async Task> GetDiscoveryDocument()
{
//
try
{
//
var result = await IdentityProvider
.RequestDiscoveryDocument();
//
// Ceck Response Result ...
if (result.IsError)
{
XException.InvalidConfiguration.Throw();
}
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
///
/// Authenticate User
///
///
/// Sample request:
///
/// {
/// "password": "",
/// "userSelectBy": "",
/// }
///
///
/// User Login Required Info, an instance of XLoginRequest
/// an instance of XTokenResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost("Authenticate")]
public virtual async Task> Authenticate(
[FromBody] XLoginRequest model
)
{
try
{
//
// Validate Args ...
if (!ModelState.IsValid)
{
XException.InvalidArgs.Throw();
}
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotEmpty(
model.UserSelectBy,
model.Password
)
.ValidateGroupAsync();
//
var result = await IdentityProvider
.Authenticate(model);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
///
/// Authenticate User
///
///
/// Sample request:
///
/// {
/// "language": "fa-IR"
/// "password": "",
/// "userSelectBy": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// User Login Required Info, an instance of XLoginRequest
/// an instance of XLoginResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost("Login")]
public virtual async Task> Login(
[FromBody] XLoginRequest model
)
{
try
{
//
// Validate Args ...
if (!ModelState.IsValid)
{
XException.InvalidArgs.Throw();
}
await ValidationProvider
.GroupValidationBuilder()
.AddNotNull(
model,
model.Device)
.AddNotEmpty(
model.Language,
model.UserSelectBy,
model.Password
)
.ValidateGroupAsync();
//
var result = await IdentityProvider
.Login(model);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
///
/// Refresh Expired Tokens
///
///
/// in addition to AccessToken, you had to pass RefreshToken due to Headers
///
/// an instance of XTokenResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost("RefreshTokens")]
public virtual async Task> RefreshTokens()
{
//
try
{
//
// Retrieve Toke Response ...
var model = await RetrieveTokensAsXTokenResponse();
//
// Validate Args ...
ValidationProvider
.GroupValidationBuilder()
.AddNotNull(model)
.AddNotEmpty(
model.AccessToken,
model.RefreshToken)
.ValidateGroup();
//
var result = await IdentityProvider
.RefreshTokens(model);
//
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Open Actions ...
///
/// Retriev User Info Based on Open Actions ...
///
///
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("GetUserInfo")]
public virtual async Task> GetUserInfo(
[FromHeader] string token,
[FromQuery] string request
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder()
.AddNotEmpty(token)
.AddNotEmpty(request)
.ValidateGroupAsync();
//
var result = await IdentityProvider.GetUserInfo(
token: token,
request: request
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
///
/// Retriev User Info Based on Open Actions ...
///
///
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("GetUserInfoByDevice")]
public virtual async Task> GetUserInfoByDevice(
[FromQuery] string userSelectByParam,
[FromBody] XDeviceDto device
)
{
//
// Do Action ...
try
{
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder()
.AddNotEmpty(userSelectByParam)
.AddNotNull(device)
.ValidateGroupAsync();
//
var result = await IdentityProvider.GetUserInfo(
userSelectByParam: userSelectByParam,
device: device
);
//
// Return Result
return Ok(result
.ToDynamicObject());
}
catch (Exception ex)
{
//
var result = GetExceptionActionResult(ex);
return result;
}
}
#endregion
//
#region Registration ...
///
/// Check a UserName is Available For Registration or not
///
/// an string value which represent desired username
/// a boolean value
[AllowAnonymous]
[RequireXPowered]
[HttpGet ("CanRegisterUserName/{userName?}")]
public virtual async Task> CanRegisterUserName (
[FromRoute] string userName
) {
//
// Do Action ...
try {
//
// Validate Args ...
ValidationProvider.NotEmpty (userName);
//
// Validate Type ...
var type = userName.GetUserSelectByType ();
if (type != XUserSelectBy.Username) {
XException.InvalidArgs.Throw ();
}
//
var result = await IdentityProvider
.CanRegister (userName);
//
// Return Result
return Ok (result);
} catch (Exception ex) {
//
var result = GetExceptionActionResult (ex);
//
return result;
}
}
///
/// Check a Mobile Number is Available For Registration or not
///
/// an string value which represent desired mobile number
/// a boolean value
[AllowAnonymous]
[RequireXPowered]
[HttpGet ("CanRegisterMobileNumber/{mobileNumber?}")]
public virtual async Task> CanRegisterMobileNumber (
[FromRoute] string mobileNumber
) {
//
// Do Action ...
try {
//
// Validate Args ...
ValidationProvider.NotEmpty (mobileNumber);
//
// Validate Type ...
var type = mobileNumber.GetUserSelectByType ();
if (type != XUserSelectBy.MobileNumber) {
XException.InvalidArgs.Throw ();
}
//
var result = await IdentityProvider
.CanRegister (mobileNumber);
//
// Return Result
return Ok (result);
} catch (Exception ex) {
//
var result = GetExceptionActionResult (ex);
//
return result;
}
}
///
/// Check a Email Address is Available For Registration or not
///
/// an string value which represent desired email address
/// a boolean value
[AllowAnonymous]
[RequireXPowered]
[HttpGet ("CanRegisterEmail/{email?}")]
public virtual async Task> CanRegisterEmail (
[FromRoute] string email
) {
//
// Do Action ...
try {
//
// Validate Args ...
ValidationProvider.NotEmpty (email);
//
// Validate Type ...
var type = email.GetUserSelectByType ();
if (type != XUserSelectBy.Email) {
XException.InvalidArgs.Throw ();
}
//
var result = await IdentityProvider
.CanRegister (email);
//
// Return Result
return Ok (result);
} catch (Exception ex) {
//
var result = GetExceptionActionResult (ex);
//
return result;
}
}
///
/// Recieve some Basic Informations and Start Registration Proccess
/// if they Valid
///
/// Registration Proccess Starts with Invoking this Action
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - FirstName: user's FirstName.
/// - LastName: user's LastName.
/// - DateOfBirth: user's dob date.
/// - MobileNumber: user's MobileNumber optional.
/// - Email: user's Email optional.
/// - ActionToken: user's requested action token for this action (if user invited).
/// - Device: user's client device which is an instance of XDevice.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "firstName": "",
/// "lastName": "",
/// "dateOfBirth": "",
/// "email": "",
/// "mobileNumber": "",
/// "actionToken": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("RequestRegistration")]
public virtual async Task> RequestRegistration (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.FirstName,
model.LastName)
.AddNotNull (
model.Device,
model.DateOfBirth)
.ValidateGroupAsync ();
//
// Get Request ...
var result = await IdentityProvider
.RequestRegistration (
model
);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
//
return exResult;
}
}
///
/// Add User Account Informations
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - UserName: user name.
/// - Password: assigne password.
/// - Device: user's client device which is an instance of XDevice.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "userName": "",
/// "password": "",
/// "actionToken": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("AddAccountInfo")]
public virtual async Task> AddAccountInfo (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.ActionToken,
model.UserName,
model.Password)
.AddNotNull (model.Device)
.ValidateGroupAsync ();
//
// Get Request ...
var result = await IdentityProvider
.AddAccountInfo (
model
);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Upload and Attach a Profile Image for User. this is an Optional Step
///
/// user's requested action token
/// an instance of IFormFile for user's Avatar
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("AttachProfileImage")]
public virtual async Task> AttachProfileImage (
[FromForm] string actionToken, [FromForm] IFormFile file
) {
//
// Do Action ...
try {
//
// Validate Args ...
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (actionToken)
.AddNotNull (file)
.ValidateGroupAsync ();
//
var result = await IdentityProvider
.AttachProfileImage (
actionToken,
file
);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Finish Registrationn Proccess
///
///
/// for this action you have to provide:
/// - a proper User Identifier such as: (UserId, UserName, Email or MobileNumber).
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - Password: assigne password.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application Login URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "userName": "",
/// "password": "",
/// "returnUrl": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
///
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("FinishRegistration")]
public virtual async Task FinishRegistration (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.Password,
model.ReturnUrl)
.AddNotNull (model.Device)
.AddUrl (model.ReturnUrl)
.ValidateGroupAsync ();
//
var userSelectByParam = IdentityProvider
.GetUserSelectByParam (model);
ValidationProvider
.NotEmpty (userSelectByParam);
//
// Get Request ...
await IdentityProvider
.FinishRegistration (model);
//
return Ok ();
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
//
return exResult;
}
}
///
/// Request Registration Confirm
///
///
/// for this action you have to provide:
/// - a UserSelectedBy identifier which represet User.
/// - Lang: client device currently used locale, such as: en-US.
/// - Password: user's current active password.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application Confirm Registration URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "userId": ""
/// "password": "",
/// "returnUrl": "http://localhost/confirm",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
///
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("RequestConfirmRegistration")]
public virtual async Task RequestConfirmRegistration (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.Password,
model.ReturnUrl)
.AddNotNull (model.Device)
.AddUrl (model.ReturnUrl)
.ValidateGroupAsync ();
//
// Get UserSelect By Param ...
var userSelectByParam = model.GetUserSelectByParam ();
ValidationProvider.NotEmpty (userSelectByParam);
//
await IdentityProvider
.RequestConfirmRegistration (model);
//
return Ok ();
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Confirm Registration
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application Login URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "actionToken": ""
/// "returnUrl": "http://localhost/login",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
///
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("ConfirmRegistration")]
public virtual async Task ConfirmRegistration (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.ActionToken,
model.ReturnUrl
)
.AddNotNull (model.Device)
.ValidateGroupAsync ();
//
// Get Request ...
await IdentityProvider
.ConfirmRegistration (model);
//
return Ok ();
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Request For Mobile Number Change/Confirm
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - Password: user's current active password.
/// - MobileNumber: which phone number is going to confirm.
/// - Device: user's client device which is an instance of XDevice.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "password": "",
/// "mobileNumber": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("RequestConfirmMobile")]
public virtual async Task> RequestConfirmMobile (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.Password,
model.MobileNumber)
.AddNotNull (model.Device)
.AddMobileNumber (model.MobileNumber)
.ValidateGroupAsync ();
//
// Get UserSelect By Param ...
var userSelectByParam = GetUserSelectByParam (
model,
excludes : [
XUserSelectBy.Email,
XUserSelectBy.MobileNumber
]);
//
// Get Request ...
var result = await IdentityProvider
.RequestConfirmMobile (model);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Confirm Requested Mobile Number
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - Device: user's client device which is an instance of XDevice.
/// - MobileVerificationCode: a verification code which produced due Request Action.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "actionToken": ""
/// "mobileVerificationCode": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("ConfirmMobileNumber")]
public virtual async Task> ConfirmMobileNumber (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.MobileVerificationCode,
model.ActionToken
)
.AddNotNull (model.Device)
.ValidateGroupAsync ();
//
// Get Request ...
var result = await IdentityProvider
.ConfirmMobileNumber (model);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Request For Email Address Change/Confirm
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - Password: user's current active password.
/// - Email: which email address is going to confirm.
/// - Device: user's client device which is an instance of XDevice.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "password": "",
/// "email": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("RequestConfirmEmail")]
public virtual async Task> RequestConfirmEmail (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.Email,
model.Password)
.AddNotNull (model.Device)
.AddEmailAddress (model.Email)
.ValidateGroupAsync ();
//
// Get UserSelect By Param ...
var userSelectByParam = GetUserSelectByParam (
model,
excludes : new List {
XUserSelectBy.Email,
XUserSelectBy.MobileNumber
});
//
// Get Request ...
var result = await IdentityProvider
.RequestConfirmEmail (model);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Confirm Requested Email Address
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - Device: user's client device which is an instance of XDevice.
/// - EmailVerificationCode: a verification code which produced due Request Action.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "actionToken": ""
/// "emailVerificationCode": "",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("ConfirmEmailAddress")]
public virtual async Task> ConfirmEmailAddress (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.EmailVerificationCode,
model.ActionToken
)
.AddNotNull (model.Device)
.ValidateGroupAsync ();
//
// Get Request ...
var result = await IdentityProvider
.ConfirmEmailAddress (model);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Request Reset Password Action
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application ResetPassword URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "returnUrl": "http://localhost/reset-password",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
/// an instance of XActionResponse
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("RequestResetPassword")]
public virtual async Task> RequestResetPassword (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.ReturnUrl)
.AddNotNull (model.Device)
.AddUrl (model.ReturnUrl)
.ValidateGroupAsync ();
//
// Get UserSelect By Param ...
var userSelectByParam = GetUserSelectByParam (
model,
excludes : new List {
XUserSelectBy.Email,
XUserSelectBy.MobileNumber
});
//
// Get Request ...
var result = await IdentityProvider
.RequestResetPassword (model);
//
return Ok (result
.ToDynamicObject ());
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
///
/// Reset a User's Password
///
///
/// for this action you have to provide:
/// - Lang: client device currently used locale, such as: en-US.
/// - ActionToken: user's requested action token for this action.
/// - NewPassword: user's new password to change.
/// - Device: user's client device which is an instance of XDevice.
/// - ReturnUrl: client application Login URL.
///
/// Sample request:
///
/// {
/// "lang": "fa-IR",
/// "actionToken": "",
/// "newPassword": "",
/// "returnUrl": "http://localhost/login",
/// "device": {
/// "os":"Mac",
/// "browser":"Chrome",
/// "osVersion":"mac-os-x-15",
/// "userAgent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36",
/// "deviceType":3,
/// "identifier":"[Mac]-[mac-os-x-15]-[3]-[Chrome]-[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) x-framework-test/0.0.0 Chrome/87.0.4280.141 Electron/11.2.0 Safari/537.36]",
/// "token":"96f400dd9aa5c57a8cec9d6f4775bad3"
/// }
/// }
///
///
/// an instance of XActionRequest class which provider requirement for action
///
[AllowAnonymous]
[RequireXPowered]
[HttpPost ("ResetPassword")]
public virtual async Task ResetPassword (
[FromBody] XActionRequest model
) {
//
// Do Action ...
try {
//
// Validate Args ...
if (!ModelState.IsValid) {
XException.InvalidArgs.Throw ();
}
await ValidationProvider
.GroupValidationBuilder ()
.AddNotEmpty (
model.Lang,
model.ActionToken,
model.NewPassword,
model.ReturnUrl)
.AddNotNull (model.Device)
.ValidateGroupAsync ();
//
// Get Request ...
await IdentityProvider
.ResetPassword (model);
//
return Ok ();
} catch (Exception ex) {
//
var exResult = GetExceptionActionResult (ex);
return exResult;
}
}
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityApiController.cs
using xCommons.Providers;
using xCommons.Attributes;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
namespace xIdentityService.Controllers
{
///
/// Base Identity Api Controller
///
[ApiController]
[RequireXPowered(true)]
[Route("api/[controller]")]
[Produces("application/json")]
public abstract class XBaseIdentityApiController : XBaseIdentityController
{
protected XBaseIdentityApiController(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{ }
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityApiV1Controller.cs
using xCommons.Providers;
using xCommons.Attributes;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
namespace xIdentityService.Controllers
{
///
/// Base Identity Api V1 Controller
///
[ApiController]
[ApiVersion("1.0")]
[RequireXPowered(true)]
[Route("api/v{version:apiVersion}/[controller]")]
public abstract class XBaseIdentityApiV1Controller : XBaseIdentityApiController
{
protected XBaseIdentityApiV1Controller(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
identityProvider,
validationProvider
)
{ }
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseIdentityController.cs
using xModels.Dtos;
using xCommons.Constants;
using xCommons.Providers;
using xCommons.Extensions;
using xCommons.Controllers;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using xCommons.Configurations;
using Microsoft.AspNetCore.Mvc;
using xIdentityModels.Constants;
using System.Collections.Generic;
using xIdentityService.Constants;
using xIdentityModels.Extensions;
using xIdentityService.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authentication;
namespace xIdentityService.Controllers
{
public abstract class XBaseIdentityController : XBaseController
{
//
public IXIdentityProvider IdentityProvider { get; }
protected XBaseIdentityController(
ILogger logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(
logger,
appConfiguration,
validationProvider
)
{
IdentityProvider = identityProvider;
}
//
#region NonActions ...
///
/// Retrieve Connection ID for Hubs ...
///
///
[NonAction]
public string GetConnectionId()
{
//
var result = "";
//
var headerKey = XHeader.ConnectionId.GetStringValue();
//
// Check if Connection ID is Provided ...
if (Request.Headers.ContainsKey(headerKey))
{
result = Request.Headers[headerKey];
}
//
return result;
}
///
/// Extract Checksum From Headers ...
///
///
[NonAction]
public string GetRequestChecksum()
{
//
var result = string.Empty;
//
var headerKey = XHeader.ChecksumDigest.GetStringValue();
//
// Check if Connection ID is Provided ...
if (Request.Headers.ContainsKey(headerKey))
{
result = Request.Headers[headerKey];
}
//
return result;
}
///
/// Extract ApiKey From Headers ...
///
///
[NonAction]
public string GetRequestApiKey()
{
//
var result = string.Empty;
//
var headerKey = XHeader.ApiKey.GetStringValue();
//
// Check if Connection ID is Provided ...
if (Request.Headers.ContainsKey(headerKey))
{
result = Request.Headers[headerKey];
}
//
return result;
}
///
/// Retrieve User Identifier Base on XActionRequest
///
///
///
///
///
[NonAction]
public string GetUserSelectByParam(
XActionRequest model,
bool forceNotNull = true,
ICollection excludes = null
)
{
//
// Validate Args ...
ValidationProvider.NotNull(model);
//
var result = IdentityProvider.GetUserSelectByParam(
model,
forceNotNull,
excludes
);
//
return result;
}
///
/// Retrieve Access Token
///
///
[NonAction]
public async Task GetAccessToken()
{
//
var accessToken = Request.Headers[XAuthorization.Header].ToString();
if (accessToken.IsNullOrEmpty())
{
//
accessToken = await HttpContext
.GetTokenAsync(XAuthorization.AccessToken);
}
//
if (accessToken
.ToNormalString()
.Contains(XAuthorization.TokenIdentifier
.ToNormalString()))
{
//
accessToken = accessToken
.Remove(0, XAuthorization.TokenIdentifier.Length);
}
//
return accessToken;
}
///
/// Retrieve Refresh Token
///
///
[NonAction]
public async Task GetRefreshToken()
{
//
var refreshToken = Request.Headers[XAuthorization.RefreshToken].ToString();
if (refreshToken.IsNullOrEmpty())
{
//
refreshToken = await HttpContext
.GetTokenAsync(XAuthorization.RefreshToken);
}
//
return refreshToken;
}
///
/// Retrieve Access Token Expiration Date
///
///
[NonAction]
public async Task GetTokenExpiresAt()
{
//
var expiresAtStr = Request.Headers[XAuthorization.ExpiresAt].ToString();
if (expiresAtStr.IsNullOrEmpty())
{
//
expiresAtStr = await HttpContext
.GetTokenAsync(XAuthorization.ExpiresAt);
}
//
var expiresAt = expiresAtStr.ConvertTo();
//
return expiresAt;
}
///
/// Retrieve All Required Tokens
///
///
[NonAction]
public async Task RetrieveTokensAsXLoginResponse()
{
//
var accessToken = await GetAccessToken();
var refreshToken = await GetRefreshToken();
var expiresAt = await GetTokenExpiresAt();
//
return new XLoginResponse
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
///
/// Retrieve All Required Tokens
///
///
[NonAction]
public async Task RetrieveTokensAsXTokenResponse()
{
//
var accessToken = await GetAccessToken();
var refreshToken = await GetRefreshToken();
var expiresAt = await GetTokenExpiresAt();
//
return new XTokenResponse
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
///
/// Retrive UserInfo
///
///
[NonAction]
public async Task GetUserInfo()
{
//
var claims = User.Claims ?? null;
if (!claims.HasChild())
{
return null;
}
//
var xTokens = await RetrieveTokensAsXTokenResponse();
var result = new XUserClaimsInfoDto(
xTokens.AccessToken,
xTokens.RefreshToken,
xTokens.ExpiresAt,
User.Claims
);
//
return result;
}
///
/// Validate User Authenticated and Retrieve User Info
///
///
[NonAction]
public async Task ValidateAndGetUserInfo()
{
//
if (!User.Identity.IsAuthenticated)
{
XException.NotAuthorized.Throw();
}
//
var result = await GetUserInfo();
if (result.IsNull())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
///
/// Get Authenticated ApiKey Person ...
///
///
[NonAction]
public XPersonDto GetApiKeyPerson()
{
//
var result = User.ExtractApiKeyUser();
return result;
}
///
/// Validate and Get Authenticated ApiKey Person ...
///
///
[NonAction]
public XPersonDto ValidateAndGetApiKeyPerson()
{
//
var result = User.ExtractApiKeyUser();
if (result.IsNullOrDefault())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
///
/// Get Authenticated JWT Person ...
///
///
[NonAction]
public XPersonDto GetAuthenticatedPerson()
{
//
var result = User.ExtractAuthenticatedUser();
return result;
}
///
/// Validate and Get Authenticated JWT Person ...
///
///
[NonAction]
public XPersonDto ValidateAndGetAuthenticatedPerson()
{
//
var result = User.ExtractAuthenticatedUser();
if (result.IsNullOrDefault())
{
XException.NotAuthorized.Throw();
}
//
return result;
}
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Controllers\XBaseTestIdentityController.cs
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 logger,
XAppConfiguration appConfiguration,
IXIdentityProvider identityProvider,
XValidationProvider validationProvider
) : base(logger, appConfiguration, identityProvider, validationProvider)
{ }
//
#region ApiKey Actions ...
///
/// a simple Hello for Accessing ApiKey Authorization ...
///
///
[XApiKeyAccess]
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyAccess")]
public ActionResult HiApiKeyAccess()
{
//
var result = $"Hi ApiKey Access, is Passed ...";
//
return Ok(result);
}
///
/// a simple Hello for Accessing ApiKey Read Access ...
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyReadAccess")]
[XApiKeyAccess(Scopes = [XApiKeyScope.Read])]
public ActionResult HiApiKeyReadAccess()
{
//
var result = $"Hi ApiKey Read Access, is Passed ...";
//
return Ok(result);
}
///
/// a simple Hello for Accessing ApiKey Write Access ...
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyWriteAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Write])]
public ActionResult HiApiKeyWriteAccess()
{
//
var result = $"Hi ApiKey Write Access, is Passed ...";
//
return Ok(result);
}
///
/// a simple Hello for Accessing ApiKey Manage Access ...
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyManageAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Manage])]
public ActionResult HiApiKManageAccess()
{
//
var result = $"Hi ApiKey Manage Access, is Passed ...";
//
return Ok(result);
}
///
/// a simple Hello for Accessing ApiKey Admin Access ...
///
///
[AllowAnonymous]
[RequireXPowered]
[HttpGet("HiApiKeyAdminAccess")]
[XApiKeyAccess(scopes: [XApiKeyScope.Admin])]
public ActionResult HiApiKeyAdminAccess()
{
//
var result = $"Hi ApiKey Admin Access, is Passed ...";
//
return Ok(result);
}
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\DI\XDIHelperExtension.cs
using System;
using xCommons.Extensions;
using xCommons.Authorization;
using Microsoft.AspNetCore.Http;
using xIdentityService.Security;
using xIdentityService.Constants;
using xIdentityService.Providers;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Builder;
using xIdentityService.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using IdentityModel.AspNetCore.OAuth2Introspection;
using xHttpService.Interfaces;
using xExceptions.Constants;
namespace xIdentityService.DI
{
public static partial class XDIHelperExtension
{
///
/// Extract Module Configuration Structure from IConfiguration interface
///
///
///
public static XIdentityServiceConfiguration GetXIdentityServiceConfiguration(this IConfiguration config)
{
//
var xIdentityServiceConfigSection = config.GetSection(ConfigurationNodeNames.IDENTITY_SERVICE_NODE_NAME);
return xIdentityServiceConfigSection.Get();
}
///
/// Register Identity Based Support Http Service ...
///
///
public static void AddXIdentityHttpService(
this IServiceCollection source
)
{
//
var httpProvider = source.GetRegisteredService();
if (!httpProvider.IsNull())
{
source.AddScoped();
}
}
///
/// Register Service and All it's Requirements
///
///
///
///
public static void AddXIdentityService(
this IServiceCollection services,
IConfiguration configuration,
ServiceLifetime lifeTime = ServiceLifetime.Singleton
)
{
//
var identityConfiguration = configuration.GetXIdentityServiceConfiguration();
AddIdentityService(
services,
identityConfiguration,
lifeTime
);
}
///
/// Register Service and All it's Requirements
///
///
///
///
public static void AddXIdentityService(
this IServiceCollection services,
XIdentityServiceConfiguration configuration,
ServiceLifetime lifeTime = ServiceLifetime.Singleton
)
{
AddIdentityService(services, configuration, lifeTime);
}
///
/// Register Custome Token Provider
///
///
///
///
public static void AddXTokenProvider(
this IServiceCollection services,
ServiceLifetime lifeTime = ServiceLifetime.Singleton
)
where T : IXTokenProvider
{
//
Console.WriteLine("IdentityService: Add Custom Token Provider ...");
services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(T), lifeTime));
}
///
/// Register Person Service ...
///
///
///
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 ...");
}
///
/// Register Policy Handler Service ...
///
///
public static void AddXPolicyHandler(
this IServiceCollection source
)
{
source.AddSingleton();
}
public static void AddXRoleHierarchyResolver(
this IServiceCollection source
)
{
//
// Check Provider ...
var providerService = source.GetRegisteredService();
if (providerService.IsNull())
{
XException.InvalidConfiguration.Throw();
}
//
source.AddScoped();
}
///
/// Use Authentication
///
///
public static void UseXIdentityService(this IApplicationBuilder app)
{
app.UseAuthentication();
}
//
#region Private ...
private static void AddIdentityService(
this IServiceCollection services,
XIdentityServiceConfiguration config,
ServiceLifetime lifeTime = ServiceLifetime.Singleton
)
{
//
services.AddSingleton(config);
//
// Register Policy Handler ...
services.AddXPolicyHandler();
//
var builder = services
.AddAuthentication(XAuthenticationScheme.XToken.GetStringValue());
//
// Add JWT Handler ...
builder.AddJwtBearer(
XAuthenticationScheme.XToken.GetStringValue(), options =>
{
//
options.Authority = config.Authority;
options.TokenValidationParameters.ValidateAudience = false;
options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" };
//
options.ForwardDefaultSelector = context =>
{
//
var path = context.Request.Path.Value;
//
var fromHeader = TokenRetrieval.FromAuthorizationHeader();
var fromQuery = TokenRetrieval.FromQueryString();
var bearerToken = fromHeader(context.Request) ?? fromQuery(context.Request);
//
var result = XAuthenticationScheme.XToken.GetStringValue();
if (!bearerToken.IsNull() && !bearerToken.Contains("."))
{
result = XAuthenticationScheme.XIntrospection.GetStringValue();
}
//
return result;
};
});
//
// Add OAuthIntrospect ...
builder.AddOAuth2Introspection(
XAuthenticationScheme.XIntrospection.GetStringValue(), options =>
{
//
options.Authority = config.Authority;
options.ClientId = config.ApiName;
options.ClientSecret = config.ClientSecret;
//
options.TokenRetriever = new Func(req =>
{
//
var fromHeader = TokenRetrieval.FromAuthorizationHeader();
var fromQuery = TokenRetrieval.FromQueryString();
//
var bearerToken = fromHeader(req) ?? fromQuery(req);
//
return bearerToken;
});
});
//
// Register Authorization Handler ...
services.AddSingleton();
Console.WriteLine("IdentityService: register Authorization Handlers ...");
//
// Register Identity Provider ...
services.Add(new ServiceDescriptor(typeof(IXIdentityProvider), typeof(XIdentityProvider), lifeTime));
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 ...
IXTokenProvider xTokenProvider = null;
try
{
xTokenProvider = services.GetRegisteredService();
}
catch { }
if (xTokenProvider.IsNull())
{
//
Console.WriteLine("IdentityService: there is no Custom Token Provider, Adding InMemoryTokenProvider instead ...");
services.Add(new ServiceDescriptor(typeof(IXTokenProvider), typeof(XInMemoryTokenProvider), lifeTime));
}
//
// Adding Security Provider ...
services.Add(new ServiceDescriptor(typeof(IXSecurityProvider), typeof(XSecurityProvider), lifeTime));
Console.WriteLine("IdentityService: Register Security Provider ...");
}
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\AuthorizationPolicyBuilderExtensions.cs
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
namespace xIdentityService.Extensions {
public static class AuthorizationPolicyBuilderExtensions {
///
/// Adds a policy to check for required scopes.
///
///
/// List of any required scopes. The token must contain at least one of the listed scopes.
///
public static AuthorizationPolicyBuilder RequireScope (this AuthorizationPolicyBuilder builder, params string[] scope) {
return builder.RequireClaim (JwtClaimTypes.Scope, scope);
}
}
///
/// Helper for creating scope-related policies
///
public static class ScopePolicy {
///
/// Creates a policy to check for required scopes.
///
/// List of any required scopes. The token must contain at least one of the listed scopes.
///
public static AuthorizationPolicy Create (params string[] scopes) {
return new AuthorizationPolicyBuilder ()
.RequireScope (scopes)
.Build ();
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\HttpContextExtensions.cs
using xCommons.Constants;
using xCommons.Extensions;
using System.Threading.Tasks;
using xIdentityModels.Models;
using Microsoft.AspNetCore.Http;
using xIdentityService.Constants;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.DependencyInjection;
namespace xIdentityService.Extensions
{
public static class HttpContextExtensions
{
///
/// Retrieve Authentication Service ...
///
///
///
public static IAuthenticationService GetAuthenticationService(this HttpContext context)
{
//
var result = context.RequestServices
.GetRequiredService();
//
return result;
}
///
/// Retrieve Specific Token from HttpContext ...
///
///
///
///
///
public static async Task GetXTokenAsync(
this HttpContext context,
string tokenName,
XAuthenticationScheme scheme = XAuthenticationScheme.XToken
)
{
//
// Validate Args ...
if (tokenName.IsNullOrEmpty())
{
return null;
}
//
var authService = context.GetAuthenticationService();
if (authService.IsNull())
{
return null;
}
//
var authResult = await authService
.AuthenticateAsync(
context,
scheme
.GetStringValue()
);
//
var result = authResult?.Properties?
.GetTokenValue(tokenName);
return result;
}
///
/// Retrieve Access Token
///
///
public static async Task GetAccessToken(this HttpContext context)
{
//
var accessToken = context.Request.Headers[XAuthorization.Header]
.ToString();
if (accessToken.IsNullOrEmpty())
{
accessToken = await context
.GetTokenAsync(XAuthorization.AccessToken);
}
//
if (accessToken
.ToNormalString()
.Contains(XAuthorization.TokenIdentifier
.ToNormalString()))
{
accessToken = accessToken
.Remove(0, XAuthorization.TokenIdentifier.Length);
}
//
return accessToken;
}
///
/// Retrieve Refresh Token
///
///
public static async Task GetRefreshToken(this HttpContext context)
{
//
var refreshToken = context.Request.Headers[XAuthorization.RefreshToken]
.ToString();
if (refreshToken.IsNullOrEmpty())
{
refreshToken = await context
.GetTokenAsync(XAuthorization.RefreshToken);
}
//
return refreshToken;
}
///
/// Retrieve Access Token Expiration Date
///
///
public static async Task GetTokenExpiresAt(this HttpContext context)
{
//
var expiresAtStr = context.Request.Headers[XAuthorization.ExpiresAt]
.ToString();
if (expiresAtStr.IsNullOrEmpty())
{
expiresAtStr = await context
.GetTokenAsync(XAuthorization.ExpiresAt);
}
//
var expiresAt = expiresAtStr.ConvertTo();
//
return expiresAt;
}
///
/// Retrieve All Required Tokens
///
///
public static async Task RetrieveTokensAsXTokenResponse(this HttpContext context)
{
//
var accessToken = await GetAccessToken(context);
var refreshToken = await GetRefreshToken(context);
var expiresAt = await GetTokenExpiresAt(context);
//
return new XTokenResponse
{
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
///
/// Retrieve Request Path ...
///
///
///
public static string GetRequestPath(this HttpContext source)
{
//
var result = source.Request.GetRequestPath();
return result;
}
///
/// Retrieve Request Path ...
///
///
///
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;
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\StreamExtensions.cs
using System.IO;
using System.Linq;
using System.Threading;
using xCommons.Extensions;
using System.Collections.Generic;
namespace xIdentityService.Extensions
{
public static partial class StreamExtensions
{
///
/// Converts an Stream to Async Enumerable ...
///
///
///
///
///
public static async IAsyncEnumerable ToAsyncEnumerable(
this Stream stream,
int bufferSize = 8192,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
var buffer = new byte[bufferSize];
while (true)
{
//
int read = await stream
.ReadAsync(
buffer,
0,
buffer.Length,
cancellationToken
);
//
if (read == 0)
{
yield break;
}
//
yield return buffer.Take(read).ToArray();
}
}
///
/// Converts an Stream to Async Enumerable ...
///
///
///
///
///
public static async IAsyncEnumerable ToAsyncEnumerable(
this Stream stream,
int bufferSize = 8192,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default
)
{
//
var buffer = new byte[bufferSize];
while (true)
{
//
int read = await stream
.ReadAsync(
buffer,
0,
buffer.Length,
cancellationToken
);
if (read == 0)
{
yield break;
}
//
T chunk = default(T);
var readedBuffer = buffer.Take(read).ToArray();
var str = readedBuffer.FromBytes();
if (str.IsNullOrEmpty())
{
yield return chunk;
}
try
{
chunk = str.FromJSON();
}
catch
{ }
//
yield return chunk;
}
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XModelExtensions.cs
using xModels.Dtos;
using xIdentityModels.Dtos;
namespace xIdentityService.Extensions
{
public static class XModelExtensions
{
public static XPersonDto ToXPersonDto(this XOpenActionUserInfoDto source)
{
//
var result = new XPersonDto
{
UserId = source.UserId,
Avatar = source.Avatar,
Lastname = source.Lastname,
Username = source.Username,
Firstname = source.Firstname,
};
//
return result;
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XPolicyDefinitionExtensions.cs
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
{
///
/// Deserialize Json Array of Required Claims ...
///
///
///
public static List ToRequiredClaims(this string json)
{
//
var result = new List();
//
// Validate ...
if (json.IsNullOrEmpty())
{
return result;
}
//
try
{
//
result = json.FromJSON>();
}
catch
{ }
//
if (result.IsNull())
{
result = [];
}
//
return result;
}
///
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
///
///
/// already resolved by IXRoleHierarchyResolver
///
public static AuthorizationPolicy ToAuthorizationPolicy(
this XPolicyDefinition source,
IEnumerable 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();
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();
}
///
/// Build AuthorizationPolicy exactly like XAuthorizationHelper does ...
///
///
/// already resolved by IXRoleHierarchyResolver
///
public static AuthorizationPolicy ToAuthorizationPolicy(
this XPolicyDefinitionDto source,
IEnumerable 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();
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();
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XRequestExtensions.cs
using xCommons.Extensions;
using Microsoft.AspNetCore.Http;
using xIdentityService.Constants;
namespace xIdentityService.Extensions
{
public static class XRequestExtensions
{
///
/// Extract ApiKey from Request Headers ...
///
///
///
public static string ExtractApiKey(this HttpContext source)
{
return source.Request.ExtractApiKey();
}
///
/// Extract ApiKey from Request Headers ...
///
///
///
public static string ExtractApiKey(this HttpRequest source)
{
//
var key = XHeader.ApiKey.GetStringValue();
var result = source?.Headers?[key] ?? string.Empty;
return result;
}
///
/// Extract Client Id of Specified Request ....
///
///
///
public static string ExtractClientIP(this HttpRequest source)
{
//
var result = source?.HttpContext.Connection.RemoteIpAddress?.ToString();
return result;
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XTokenExtensions.cs
using System;
using System.Net.Http;
using xCommons.Constants;
using xExceptions.Models;
using xCommons.Extensions;
using IdentityModel.Client;
using xExceptions.Constants;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using xIdentityService.Interfaces;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Authentication;
public static partial class XTokenExtensions {
///
/// Retrieve Tokens From Headers
///
///
///
public static XLoginResponse RetrieveTokens (this HttpRequest source) {
//
var accessToken = source.Headers[XAuthorization.Header].ToString ();
var refreshToken = source.Headers[XAuthorization.RefreshToken].ToString ();
//
var expiresAtStr = source.Headers[XAuthorization.ExpiresAt].ToString ();
long expiresAt = expiresAtStr.ConvertTo ();
//
if (accessToken
.ToNormalString ()
.Contains (XAuthorization.TokenIdentifier.ToNormalString ())) {
accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length);
}
//
return new XLoginResponse {
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
}
///
/// Retrieve Tokens From HttpContext
///
///
///
public static async Task RetrieveTokens (this HttpContext source) {
//
var accessToken = await source.GetTokenAsync (XAuthorization.AccessToken);
if (accessToken
.ToNormalString ()
.Contains (XAuthorization.TokenIdentifier.ToNormalString ())) {
accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length);
}
var refreshToken = await source.GetTokenAsync (XAuthorization.RefreshToken);
var expiresAtStr = await source.GetTokenAsync (XAuthorization.ExpiresAt);
long expiresAt = expiresAtStr.ConvertTo ();
//
var headerRequestTokens = source.Request.RetrieveTokens ();
//
var result = new XLoginResponse {
AccessToken = accessToken ?? headerRequestTokens.AccessToken,
RefreshToken = refreshToken ?? headerRequestTokens.RefreshToken,
ExpiresAt = expiresAt != 0 ? expiresAt : headerRequestTokens.ExpiresAt
};
//
return result;
}
///
/// Retrieve Tokens From ActionExecutingContext
///
///
///
public static async Task RetrieveTokens (this ActionExecutingContext source) {
//
var result = await source.HttpContext.RetrieveTokens ();
return result;
}
///
/// Retrieve Tokens From XUserInfo instance
///
///
///
public static XTokenResponse RetrieveTokens (this XUserClaimsInfoDto source) {
//
var result = new XLoginResponse {
AccessToken = source.AccessToken,
RefreshToken = source.RefreshToken,
ExpiresAt = source.ExpiresAt
};
//
return result;
}
///
/// Retrieve Tokens From IHeader Dictionary
///
///
///
public static XLoginResponse RetrieveTokens (this IHeaderDictionary source) {
//
var accessToken = source[XAuthorization.Header].ToString () ?? "";
if (accessToken
.ToNormalString ()
.Contains (XAuthorization.TokenIdentifier.ToNormalString ())) {
accessToken = accessToken.Remove (0, XAuthorization.TokenIdentifier.Length);
}
//
var refreshToken = source[XAuthorization.RefreshToken].ToString () ?? "";
//
var expiresAtStr = source[XAuthorization.ExpiresAt].ToString () ?? "";
var expiresAt = expiresAtStr.ConvertTo ();
//
var result = new XLoginResponse {
AccessToken = accessToken,
RefreshToken = refreshToken,
ExpiresAt = expiresAt
};
//
return result;
}
///
/// Retrieve IXIdentityProvider from HttpContext
///
///
///
public static IXIdentityProvider GetXApiIdentityProvider (this FilterContext source) {
//
var services = source.HttpContext.RequestServices;
return (IXIdentityProvider) services
.GetService (typeof (IXIdentityProvider));
}
///
/// Generate XLoginResponse instance based on TokenResponse
///
///
///
public static XLoginResponse CreateXLoginResponse (this TokenResponse source) {
//
if (source.IsNull () ||
source.IsError) {
XException.InvalidToken.Throw ();
}
//
var expiresAt = new DateTimeOffset (DateTime.UtcNow)
.ToUnixTimeSeconds () +
source.ExpiresIn;
//
var result = new XLoginResponse {
AccessToken = source.AccessToken,
RefreshToken = source.RefreshToken,
ExpiresAt = expiresAt
};
//
return result;
}
///
/// Add Authorization Tokens in Headers of
/// Specific IHeaderDictionary instance
///
///
///
///
public static void SetXAuthenticationTokens (
this IHeaderDictionary source,
XLoginResponse model,
string secret = null
) {
//
source.Remove (XAuthorization.Header);
source.Remove (XAuthorization.RefreshToken);
source.Remove (XAuthorization.ExpiresAt);
source.Remove (XAuthorization.RevisionChecksum);
//
source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}");
source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}");
source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}");
//
if (!secret.IsNullOrEmpty ()) {
var revisionChecksum = model.GetRevisionChecksum (secret);
source.Add (XAuthorization.RevisionChecksum, revisionChecksum);
}
}
///
/// Add Authorization Tokens in Headers of
/// Specific IHeaderDictionary instance
///
///
///
public static void SetXAuthenticationTokens (this HttpRequestHeaders source, XLoginResponse model) {
//
source.Remove (XAuthorization.Header);
source.Remove (XAuthorization.RefreshToken);
source.Remove (XAuthorization.ExpiresAt);
source.Remove (XAuthorization.RevisionChecksum);
//
source.Add (XAuthorization.Header, $"{XAuthorization.TokenIdentifier}{model.AccessToken}");
source.Add (XAuthorization.RefreshToken, $"{model.RefreshToken}");
source.Add (XAuthorization.ExpiresAt, $"{model.ExpiresAt}");
}
///
/// Add Authorization Tokens in Headers of
/// Specific HttpRequest instance
///
///
///
public static void SetXAuthenticationTokens (this HttpRequest source, XLoginResponse model) {
source.Headers.SetXAuthenticationTokens (model);
}
///
/// Add Authorization Tokens in Headers of
/// Specific HttpRequest instance
///
///
///
public static void SetXAuthenticationTokens (this HttpRequestMessage source, XLoginResponse model) {
source.Headers.SetXAuthenticationTokens (model);
}
///
/// Add ReNewed Authorization Tokens in Headers of
/// Specific Response.
/// Later in HttpInterceptors we can Look for AccessToken-ReNewed
/// header Value and Renew User Tokens based on it
///
///
///
///
public static void SetXAuthenticationTokens (
this HttpResponse source,
XLoginResponse model,
string secret
) {
source.Headers.SetXAuthenticationTokens (model, secret);
}
///
/// Determines a Token Can Refrsh or not
///
///
///
public static bool IsRefreshable (this XLoginResponse source) {
//
var containsTokenData = !source.IsNull () &&
!source.AccessToken.IsNullOrEmpty () &&
!source.RefreshToken.IsNullOrEmpty ();
if (!containsTokenData) {
return false;
}
//
var current = new DateTimeOffset (DateTime.UtcNow)
.ToUnixTimeSeconds ();
//
// var result = current > source.ExpiresAt || current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration;
var result = current > source.ExpiresAt - XAuthorization.ThresholdBeforeTokenExpiration;
//
return result;
}
///
/// Generate a Revision Checksum for new Tokens
///
///
///
///
public static string GetRevisionChecksum (this XLoginResponse source, string secret) {
return (source.AccessToken +
secret +
source.RefreshToken +
secret +
source.ExpiresAt.ToString ()
)
.ToMd5String ();
}
///
/// Generate a Revision Checksum for new Tokens
///
///
///
///
public static string GetRevisionChecksum (this XTokenResponse source, string secret) {
return (source.AccessToken +
secret +
source.RefreshToken +
secret +
source.ExpiresAt.ToString ()
)
.ToMd5String ();
}
///
/// Check an XLoginResponse instance is Valid with it's revision
///
///
///
///
///
public static bool ValidateRevisionChecksum (this XLoginResponse source, string checksum, string secret) {
//
var xChecksum = source.GetRevisionChecksum (secret);
return checksum == xChecksum;
}
///
/// Check an XTokenResponse instance is Valid with it's revision
///
///
///
///
///
public static bool ValidateRevisionChecksum (this XTokenResponse source, string checksum, string secret) {
//
var xChecksum = source.GetRevisionChecksum (secret);
return checksum == xChecksum;
}
///
/// Retrieve Exception Details if Fails
///
///
///
public static Exception GetException (this TokenResponse source) {
//
// Validate Args ...
if (source.IsNull () || !source.IsError) {
return XException.ActionFailed.ToException ();
}
//
XError error = source.ErrorDescription.FromJSON ();
return error.ToException ();
}
///
/// Convert XTokenResponse to Header Dictionary
///
///
///
public static IDictionary ToHeaderDictionary (this XTokenResponse source) {
//
var result = new Dictionary { { XAuthorization.RefreshToken, source.RefreshToken },
{ XAuthorization.ExpiresAt, source.ExpiresAt.ToString () }
};
//
return result;
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Extensions\XUserClaimsInfoDtoExtensions.cs
using xCommons.Extensions;
using xIdentityModels.Models;
using xIdentityModels.Constants;
namespace xIdentityService.Extensions {
public static class XUserClaimsInfoDtoExtensions {
public static string GetUserSelectByParam (
this XUserClaimsInfoDto source,
XUserSelectBy userSelectBy = XUserSelectBy.Username
) {
//
var result = "";
//
switch (userSelectBy) {
//
case XUserSelectBy.ID:
result = source.UserId;
break;
//
case XUserSelectBy.Username:
result = source.UserName;
break;
//
case XUserSelectBy.Email:
result = source.Email;
break;
//
case XUserSelectBy.MobileNumber:
result = source.PhoneNumber;
break;
}
//
if (result.IsNullOrEmpty ()) {
//
if (!source.UserId.IsNullOrEmpty ()) {
result = source.UserId;
} else if (!source.UserName.IsNullOrEmpty ()) {
result = source.UserName;
} else if (!source.Email.IsNullOrEmpty ()) {
result = source.Email;
} else if (!source.PhoneNumber.IsNullOrEmpty ()) {
result = source.PhoneNumber;
}
}
//
return result;
}
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXAuthorizationCache.cs
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);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXAuthorizationProvider.cs
using xModels.Dtos;
using System.Threading;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXAuthorizationProvider
{
//
#region Scope ...
Task> QueryScopesAsync(
XQuery query,
CancellationToken cancellationToken = default
);
Task GetScopeAsync(
string name,
CancellationToken cancellationToken = default
);
Task AddScopeAsync(
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task UpdateScopeAsync(
string name,
XScopeDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task RemoveScopeAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
#endregion
//
#region Role ...
Task> GetRolesAsync(
CancellationToken cancellationToken = default
);
Task GetRoleAsync(
string name,
CancellationToken cancellationToken = default
);
Task AddRoleAsync(
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task UpdateRoleAsync(
string name,
XRoleDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task RemoveRoleAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task CountUsersInRoleAsync(
string name,
CancellationToken cancellationToken = default
);
#endregion
//
#region Policy ...
Task> QueryPoliciesAsync(
XQuery query,
CancellationToken cancellationToken = default
);
Task GetPolicyAsync(
string name,
CancellationToken cancellationToken = default
);
Task AddPolicyAsync(
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task UpdatePolicyAsync(
string name,
XPolicyDefinitionDto item,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task RemovePolicyAsync(
string name,
XUserClaimsInfoDto userInfo,
CancellationToken cancellationToken = default
);
Task EvaluatePolicyAsync(
string name,
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
);
Task GetEffectiveAuthorizationAsync(
XUserClaimsInfoDto target,
CancellationToken cancellationToken = default
);
#endregion
//
#region Utilities ...
Task SyncAllAsync(CancellationToken cancellationToken = default);
Task InvalidateAsync(string policyName = null);
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseIdentityHttpProvider.cs
using System;
using System.IO;
using RestSharp;
using System.Net.Http;
using System.Threading;
using xCommons.Providers;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityModels.Models;
using xIdentityService.Models;
using xIdentityModels.Constants;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace xIdentityService.Interfaces
{
///
/// an interface for Identity Provided Http Based Services ...
///
public interface IXBaseIdentityHttpProvider
{
///
/// Client Base Url ...
///
///
string BaseUrl { get; }
///
/// Logger ...
///
///
ILogger Logger { get; }
///
/// Powered Value ...
///
///
string XPoweredValue { get; }
///
/// Default Client Timeout ...
///
///
int DefaultClientTimeout { get; }
///
/// Default Buffering Chunk Size ...
///
///
int DefaultBufferingChunckSize { get; }
///
/// Validation Provider ...
///
///
XValidationProvider ValidationProvider { get; }
///
/// Get an Instance of Http Client
///
///
HttpClient GetHttpClient(XTokenResponse tokens = null);
HttpClient GetHttpClient(XUserClaimsInfoDto userInfo = null);
///
/// Get an Instance of RestClient
///
///
RestClient GetRestClient(XTokenResponse tokens = null);
RestClient GetRestClient(XUserClaimsInfoDto userInfo = null);
///
/// Get an Instance of RestRequest
///
///
///
///
///
///
///
RestRequest GetRestRequet(
Enum endpoint,
bool addXPoweredValue = true,
IDictionary @params = null,
IDictionary headers = null,
IDictionary queryStrings = null
);
///
/// Handle Call Specific Request and retrieve Response
///
///
///
///
///
///
///
///
Task RunRestRequest(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
///
/// Access a Get Request Stream as AsyncEnumerable ...
///
///
///
///
///
///
///
///
///
///
///
Task StreamData(
Enum endpoint,
int bufferLength = 8194,
bool addXPoweredValue = true,
XTokenResponse tokens = null,
IDictionary @params = null,
IDictionary headers = null,
IDictionary queryStrings = null,
CancellationToken cancellationToken = default
);
///
/// Handle Call Specified Request and Retrieve XBaseRestResponse ...
///
///
///
///
///
///
///
/// an instance of XBaseRestResponse
Task> RunRestRequestByResponse(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
///
/// Get User SelectBy Param
///
///
///
///
///
string GetUserSelectByParam(
XActionRequest model,
bool forceNotNull = true,
ICollection excludes = null
);
///
/// Converts UserInfo to TokenResponse model ...
///
///
///
XTokenResponse ToTokenResponse(XUserClaimsInfoDto userInfo = null);
///
/// Prepare Url Address of Specified Enum by Filling Params
/// and Query Strings Attach ...
///
///
///
///
///
///
string PrepareUrl(
Enum endpoint,
bool attachBaseUrl = false,
IDictionary @params = null,
IDictionary queryStrings = null
);
///
/// Prepare Url Address by Filling Params
/// and Query Strings Attach ...
///
///
///
///
///
///
string PrepareUrl(
string url,
bool attachBaseUrl = false,
IDictionary @params = null,
IDictionary queryStrings = null
);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseReferenced.cs
using xModels.Base;
using System.Threading;
using xDataService.Models;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
///
/// a Referenced Service is a Service which can Referenced to other Items ...
///
public interface IXBaseReferenced
where TEntity : XBaseEntity
{
///
/// Get Reference Identifier for Specified Provider and Specified Item ...
///
///
///
///
string GetIdentifier(
string providedFor,
TReferenceKey forProvidedId
);
///
/// Check Specified Item has Refernce to Provider ...
///
///
///
///
///
///
Task IsProvidedFor(
string providedFor,
TReferenceKey forProvidedId,
TKey id,
CancellationToken cancellationToken = default
);
///
/// Add Specified Reference to Specified Item ...
///
///
///
///
///
///
///
///
///
Task AddReference(
string providedFor,
TReferenceKey forProvidedId,
TKey id,
int forIndex = 0,
XUserClaimsInfoDto userInfo = null,
string connectionId = null,
CancellationToken cancellationToken = default
);
///
/// Remove Specified Reference from Specified Item ...
///
///
///
///
///
///
///
///
///
Task RemoveReference(
string providedFor,
TReferenceKey forProvidedId,
TKey id,
int forIndex = 0,
XUserClaimsInfoDto userInfo = null,
string connectionId = null,
CancellationToken cancellationToken = default
);
///
/// Get Specified References ...
///
///
///
///
///
Task>> GetReferences(
string providedFor,
TKey id,
CancellationToken cancellationToken = default
);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXBaseReferencedController.cs
using xModels.Base;
using System.Threading;
using xDataService.Models;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXBaseReferencedController
where TEntity : XBaseEntity
{
///
/// Check an Item Has Reference to Specified ProvideFor and Specified forProvidedId ...
///
///
///
///
///
///
[HttpGet("{id}/Reference/IsProvidedFor")]
Task> IsProvidedFor(
[FromRoute] TKey id,
[FromQuery] string providedFor,
[FromQuery] object forProvidedId,
CancellationToken cancellationToken = default
);
///
/// Add a Reference to Item for Specified ProvideFor and Specified forProvidedId ...
///
///
///
///
///
///
///
[HttpPost("{id}/Reference")]
Task AddReference(
[FromRoute] TKey id,
[FromQuery] string providedFor,
[FromQuery] object forProvidedId,
[FromQuery] int forIndex = 0,
CancellationToken cancellationToken = default
);
///
/// Remove a Reference from Item for Specified ProvideFor and Specified forProvidedId ...
///
///
///
///
///
///
///
[HttpDelete("{id}/Reference")]
Task RemoveReference(
[FromRoute] TKey id,
[FromQuery] string providedFor,
[FromQuery] object forProvidedId,
[FromQuery] int forIndex = 0,
CancellationToken cancellationToken = default
);
///
/// Retrieve References of Specified Itemfor providedFor ...
///
///
///
///
///
[HttpGet("{id}/References")]
Task>>> GetReferences(
[FromRoute] TKey id,
[FromQuery] string providedFor,
CancellationToken cancellationToken = default
);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXIdentityBaseReferencedProvider.cs
using xModels.Dtos;
using xDataService.Models;
using System.Threading.Tasks;
using xIdentityModels.Models;
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
///
/// in Some Cases we have Entities Which Can Referenced for Specified
/// Provider and Types ...
/// this interface Globaly introduce all available Actions for those ...
///
/// TKey: type of Provider Models Keys ...
/// TModel: type of Dto which Referenced ...
///
public interface IXIdentityBaseReferencedProvider
{
//
#region Props ...
///
/// Provider Identifier ...
///
string Provider { get; }
#endregion
//
#region Referenced Actions ...
///
/// Get Specified Indexed Reference for Specific Provided ID ...
///
///
///
///
Task GetReference(
TKey providedForId,
int forIndex = 0
);
///
/// Retrieve all Exists References of Specific Provided ID ...
///
///
///
Task> GetAllReferences(TKey providedForId);
///
/// Extract all Referencing Models for Specified Key ...
///
///
///
Task>> GetAllReferencings(TKey providedForId);
///
/// Count References ...
///
///
///
Task CountReferences(TKey providedForId);
///
/// Retrieve References of Specific Provided ID as Query ...
///
///
///
///
Task> QueryReferences(
XQuery query,
TKey providedForId
);
///
/// Add Reference a Model to Specific Provided ID ...
///
///
///
///
///
///
Task AddReference(
TModel model,
TKey providedForId,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
);
///
/// Add Reference a Model to Specific XRefence ...
///
///
///
///
///
///
Task AddReference(
TModel model,
XReference reference,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
);
///
/// Remove Reference a Model for Specific Provided ID ...
///
///
///
///
///
///
Task RemoveReference(
TModel model,
TKey providedForId,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
);
///
/// Remove Reference a Model for Specific XRefence ...
///
///
///
///
///
///
Task RemoveReference(
TModel model,
XReference reference,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
);
///
/// Remove All References to Specified Key ...
///
///
///
///
///
Task RemoveReferences(
TKey providedForId,
string connectionId = null,
XUserClaimsInfoDto userInfo = null
);
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXIdentityHttpProvider.cs
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
{
///
/// Get an Instance of RestRequest ...
///
///
///
///
///
///
///
RestRequest GetRestRequest(
string endpoint,
bool addXPoweredValue = true,
IDictionary @params = null,
IDictionary headers = null,
IDictionary queryStrings = null
);
///
/// Handle Call Specific Request and retrieve Response
///
///
///
///
///
///
///
///
Task RunRestRequest(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
Task> RunRestRequestByResponse(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = true,
CancellationToken cancellationToken = default
);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXIdentityProvider.cs
using System;
using RestSharp;
using xModels.Dtos;
using System.Threading;
using IdentityModel.Client;
using xIdentityModels.Dtos;
using System.Threading.Tasks;
using xHttpService.Constants;
using xIdentityModels.Models;
using Microsoft.AspNetCore.Http;
using xIdentityModels.Constants;
using System.Collections.Generic;
using xIdentityModels.Navigations;
namespace xIdentityService.Interfaces
{
public partial interface IXIdentityProvider
{
//
string BaseUrl { get; }
string RevisionSecretKey { get; }
IXSecurityProvider SecurityProvider { get; }
//
#region Tools ...
string GetUserSelectByParam(
XActionRequest model,
bool forceNotNull = true,
ICollection excludes = null
);
#endregion
//
#region Tools ...
Task RunRestRequest(
RestClient client,
RestRequest request,
XHttpMethod method,
bool supportRefreshingTokens = false
);
#endregion
//
#region Authentication ...
Task RequestDiscoveryDocument();
Task RequestScopeAccessToken(string scope);
Task Validate(XTokenResponse model);
Task Introspection(XTokenResponse model);
Task Login(XLoginRequest model);
Task Logout(XTokenResponse model);
Task Authenticate(XLoginRequest model);
Task RefreshTokens(XTokenResponse model);
Task ChangePassword(
XTokenResponse tokens,
XActionRequest model
);
#endregion
//
#region Profile ...
Task> GetUserNames(
XTokenResponse tokens,
string userIds
);
Task> GetUserNameIds(
XTokenResponse tokens,
XUserNameIdRequest model
);
Task GetUserProfile(
XTokenResponse tokens,
string userSelectByParam
);
Task> QueryUsers(
XTokenResponse tokens,
XQuery query
);
Task> QueryInRoleUsers(
XTokenResponse tokens,
string role,
XQuery query,
bool forceRole = false
);
Task> QueryAvatars(
XTokenResponse tokens,
string userSelectByParam,
XQuery query
);
Task ProfileUpdateAsync(
XTokenResponse tokens,
string userSelectByParam,
XProfileUpdateRequest model
);
Task FullProfileUpdateAsync(
XTokenResponse tokens,
string userSelectByParam,
XProfileUpdateRequest request
);
Task AddAvatar(
XTokenResponse tokens,
IFormFile file
);
Task AddAvatars(
XTokenResponse tokens,
IFormFileCollection files
);
Task SetAvatar(
XTokenResponse tokens,
int avatarId
);
Task RemoveAvatars(
XTokenResponse tokens,
string avatarIds
);
#endregion
//
#region Search ...
///
/// Query Open To Search User Profiles ...
///
/// requested user's identifiers
/// how to filter results based on XQuery structure
/// an instance of XQueryResult of XUserProfileDto
Task> QueryOpenToSearchUsers(
XTokenResponse tokens,
XQuery query
);
#endregion
//
#region Registration ...
Task CanRegister(string userSelectByParam);
Task InviteUser(
XTokenResponse tokens,
XActionRequest model
);
Task RequestRegistration(
XActionRequest model
);
Task AddAccountInfo(
XActionRequest model
);
Task AttachProfileImage(
string actionToken,
IFormFile file
);
Task FinishRegistration(XActionRequest model);
Task IsConfirmedEmail(
XTokenResponse tokens,
string userSelectByParam
);
Task IsConfirmedMobile(
XTokenResponse tokens,
string userSelectByParam
);
Task RequestConfirmRegistration(XActionRequest model);
Task ConfirmRegistration(
XActionRequest model
);
Task RequestConfirmMobile(XActionRequest model);
Task ConfirmMobileNumber(XActionRequest model);
Task RequestConfirmEmail(XActionRequest model);
Task ConfirmEmailAddress(XActionRequest model);
Task RequestResetPassword(XActionRequest model);
Task ResetPassword(XActionRequest model);
#endregion
//
#region Friendship ...
Task Follow(
XTokenResponse tokens,
string destUser
);
Task Cancel(
XTokenResponse tokens,
string destUser
);
Task UnFollowFollower(
XTokenResponse tokens,
string destUser
);
Task UnFollowFollowing(
XTokenResponse tokens,
string destUser
);
Task Block(
XTokenResponse tokens,
string destUser
);
Task UnBlock(
XTokenResponse tokens,
string destUser
);
Task AcceptRequest(
XTokenResponse tokens,
string destUser
);
Task RejectRequest(
XTokenResponse tokens,
string destUser
);
Task GetFriendshipInfo(
XTokenResponse tokens,
string destUser
);
Task IsFollower(
XTokenResponse tokens,
string destUser
);
Task GetFollower(
XTokenResponse tokens,
string destUser
);
Task GetFollowerState(
XTokenResponse tokens,
string destUser
);
Task> GetFollowers(XTokenResponse tokens);
Task> GetAllFollowers(XTokenResponse tokens);
Task> GetFollowingList(XTokenResponse tokens);
Task> QueryFollowers(
XQuery query,
string destUser,
XTokenResponse tokens
);
Task IsFollowing(
XTokenResponse tokens,
string destUser
);
Task GetFollowing(
XTokenResponse tokens,
string destUser
);
Task GetFollowingState(
XTokenResponse tokens,
string destUser
);
Task> GetFollowings(XTokenResponse tokens);
Task> GetAllFollowings(XTokenResponse tokens);
Task> GetFollowersList(XTokenResponse tokens);
Task> QueryFollowings(
XQuery query,
string destUser,
XTokenResponse tokens
);
#endregion
//
#region Admin ...
Task> Ban(
XTokenResponse tokens,
XUserNameIdRequest model
);
Task> UnBan(
XTokenResponse tokens,
XUserNameIdRequest model
);
Task IsBanned(
XTokenResponse tokens,
string userSelectByParam
);
#endregion
//
#region Open Actions ...
//
XDeviceDto GetDevice();
//
Task OpenGet(
XOpenActionInnerDto model
);
//
Task GetApiKey(
XDeviceDto device,
string apiKey
);
Task GetApiKey(
XOpenActionInnerDto dto
);
Task GetApiKey(
string token,
string request
);
//
Task UseApiKey(
XDeviceDto device,
XApiKeyUsageDto apiKeyUsage
);
Task UseApiKey(
XOpenActionInnerDto dto
);
Task UseApiKey(
string token,
string request
);
//
Task GetUserInfo(
XDeviceDto device,
string userSelectByParam
);
Task GetUserInfo(
XOpenActionInnerDto dto
);
Task GetUserInfo(
string token,
string request
);
//
Task> GetUserInfos(
XDeviceDto device,
string ids
);
Task> GetUserInfos(
XOpenActionInnerDto dto
);
Task> GetUserInfos(
string token,
string request
);
#endregion
//
#region Applications ...
//
#region Application ...
///
/// Create Application ...
///
///
///
///
///
Task CreateApplication(
XTokenResponse tokens,
XApplicationDto item,
CancellationToken cancellationToken = default
);
///
/// Update Specified Application ...
///
///
///
///
///
///
Task UpdateApplication(
XTokenResponse tokens,
int id,
XApplicationDto item,
CancellationToken cancellationToken = default
);
///
/// Remove Specified Application ...
///
///
///
///
///
Task RemoveApplication(
XTokenResponse tokens,
int id,
CancellationToken cancellationToken = default
);
///
/// Get Specified Application ...
///
///
///
///
///
Task GetApplication(
XTokenResponse tokens,
int id,
CancellationToken cancellationToken = default
);
///
/// Query Applications ...
///
///
///
///
///
Task> QueryApplications(
XTokenResponse tokens,
XQuery query,
CancellationToken cancellationToken = default
);
///
/// Get All Application ...
///
///
///
///
Task> GetAllApplications(
XTokenResponse tokens,
CancellationToken cancellationToken = default
);
#endregion
//
#region XApiKey ...
///
/// Get Specified ApiKey ...
///
///
///
///
///
Task GetApiKey(
XTokenResponse tokens,
Guid id,
CancellationToken cancellationToken = default
);
///
/// Remove Specified ApiKey ...
///
///
///
///
///
Task RemoveApiKey(
XTokenResponse tokens,
Guid id,
CancellationToken cancellationToken = default
);
///
/// Update Specified ApiKey ...
///
///
///
///
///
///
Task UpdateApiKey(
XTokenResponse tokens,
Guid id,
XApiKeyDto item,
CancellationToken cancellationToken = default
);
///
/// Query ApiKeys ...
///
///
///
///
///
Task> QueryApiKeys(
XTokenResponse tokens,
XQuery query,
CancellationToken cancellationToken = default
);
///
/// Get All Specified ApiKeys ...
///
///
///
///
Task> GetAllApiKeys(
XTokenResponse tokens,
CancellationToken cancellationToken = default
);
#endregion
//
#region XApiKeyUsage ...
///
/// Add Api Key Usage ...
///
///
///
///
///
Task AddApiKeyUsage(
XTokenResponse tokens,
XApiKeyUsageDto item,
CancellationToken cancellationToken = default
);
///
/// Get Specified Api Key Usage ...
///
///
///
///
///
Task GetApiKeyUsage(
XTokenResponse tokens,
long id,
CancellationToken cancellationToken = default
);
///
/// Remove Specified Api Key Usage ...
///
///
///
///
///
Task RemoveApiKeyUsage(
XTokenResponse tokens,
long id,
CancellationToken cancellationToken = default
);
///
/// Update Specified Api Key Usage ...
///
///
///
///
///
///
Task UpdateApiKeyUsage(
XTokenResponse tokens,
long id,
XApiKeyUsageDto item,
CancellationToken cancellationToken = default
);
///
/// Query Api Key Usages ...
///
///
///
///
///
Task> QueryApiKeyUsages(
XTokenResponse tokens,
XQuery query,
CancellationToken cancellationToken = default
);
///
/// Get All Api Key Usages ...
///
///
///
///
Task> GetAllApiKeyUsages(
XTokenResponse tokens,
CancellationToken cancellationToken = default
);
#endregion
//
#region Custom ...
///
/// Show Api Key ...
///
///
///
///
///
///
Task ShowApiKey(
XTokenResponse tokens,
Guid apiKeyId,
int applicationId,
CancellationToken cancellationToken = default
);
///
/// Create Api Key ...
///
///
///
///
///
///
Task CreateApiKey(
XTokenResponse tokens,
int applicationId,
XCreateApiKeyRequest request,
CancellationToken cancellationToken = default
);
///
/// Remove Specified Api Key ...
///
///
///
///
///
///
Task RemoveApiKey(
XTokenResponse tokens,
int applicationId,
Guid apiKeyId,
CancellationToken cancellationToken = default
);
///
/// Rotate Specified Api Key ...
///
///
///
///
///
///
///
Task RotateApiKey(
XTokenResponse tokens,
int applicationId,
Guid apiKeyId,
XRotateApiKeyRequest request,
CancellationToken cancellationToken = default
);
///
/// Revoke Specified Api Key ...
///
///
///
///
///
///
Task RevokeApiKey(
XTokenResponse tokens,
int applicationId,
Guid apiKeyId,
CancellationToken cancellationToken = default
);
///
/// Retrieve Specified Application's Api Keys ...
///
///
///
///
///
Task> GetApiKeys(
XTokenResponse tokens,
int applicationId,
CancellationToken cancellationToken = default
);
///
/// Retrieve Specified Api Keys Usages ...
///
///
///
///
///
///
Task> GetApiKeyUsages(
XTokenResponse tokens,
int applicationId,
Guid apiKeyId,
CancellationToken cancellationToken = default
);
///
/// Validate Specifed Api Key ...
///
///
///
///
Task ValidateApiKey(
XApiKeyValidationRequest request,
CancellationToken cancellationToken = default
);
#endregion
#endregion
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXPersonService.cs
using xModels.Dtos;
using System.Threading.Tasks;
namespace xIdentityService.Interfaces
{
public interface IXPersonService
{
///
/// Retrieve Person ...
///
///
///
Task GetPerson(string userId);
///
/// Handle Cleanup ...
///
void Cleanup();
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXPolicyHandler.cs
using System.Collections.Generic;
namespace xIdentityService.Interfaces
{
public interface IXPolicyHandler
{
///
/// Add Specified Role ...
///
///
///
///
bool AddPolicy(
string policy,
IEnumerable requiredRoles
);
///
/// Check Specified Role Exists or not ...
///
///
///
bool HasPolicy(string policy);
///
/// Remove Specified Role ...
///
///
///
bool RemovePolicy(string policy);
///
/// Check Specified Policy passed or not ...
///
///
///
///
bool IsPolicyPassed(
string policy,
IEnumerable roles
);
}
}
### FILE: C:\Users\SaherElm\Documents\Projects\xSaherelmWorkspace\Modules\xIdentityService\Interfaces\IXPolicyProvider.cs
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 ...
///
/// retrieve whole items as queryable ...
///
/// a flag for Tracking behaviour
/// an Expression for Filter Items ...
/// an Order Builder expression for Ordering Query ...
///
IQueryable AsQueryable(
bool asNoTracking = true,
Expression> predicate = null,
Func, IOrderedQueryable> orderBuilder = null
);
///
/// retrieve an Entity by it's Id ...
///
///
///
///
///
Task GetAsync(
int id,
bool ignoreSoftDeleteds = true,
CancellationToken cancellationToken = default
);
///