Compare commits
5
Commits
a87ea5d64d
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e86b50163c | ||
|
|
bfd60e9bb3 | ||
|
|
5085fc54a4 | ||
|
|
2e8f269ae6 | ||
|
|
c4e430a98f |
@@ -27,8 +27,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("ApiKeys/{id}")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/ApiKeys/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApiKeyDto>> GetApiKey(
|
||||
[FromRoute] Guid id,
|
||||
@@ -75,8 +75,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpDelete("ApiKeys/{id}")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpDelete("Applications/ApiKeys/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApiKeyDto>> RemoveApiKey(
|
||||
[FromRoute] Guid id,
|
||||
@@ -123,8 +123,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpPut("ApiKeys/{id}")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpPut("Applications/ApiKeys/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApiKeyDto>> UpdateApiKey(
|
||||
[FromRoute] Guid id,
|
||||
@@ -173,8 +173,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("ApiKeys")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/ApiKeys")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<IEnumerable<XApiKeyDto>>> GetAllApiKeys(
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -213,8 +213,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("ApiKeys/Query")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/ApiKeys/Query")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XQueryResult<XApiKeyDto>>> QueryApiKeys(
|
||||
[FromRoute] XQuery query,
|
||||
|
||||
@@ -27,8 +27,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpPost("ApiKeys/Usages")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpPost("Applications/ApiKeys/Usages")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApiKeyUsageDto>> AddApiKeyUsage(
|
||||
[FromBody] XApiKeyUsageDto item,
|
||||
@@ -74,8 +74,8 @@ namespace xIds.Controllers
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("ApiKeys/Usages/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpGet("Applications/ApiKeys/Usages/{id}")]
|
||||
public async Task<ActionResult<XApiKeyUsageDto>> GetApiKeyUsage(
|
||||
[FromRoute] long id,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -122,8 +122,8 @@ namespace xIds.Controllers
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpDelete("ApiKeys/Usages/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpDelete("Applications/ApiKeys/Usages/{id}")]
|
||||
public async Task<ActionResult<XApiKeyUsageDto>> RemoveApiKeyUsage(
|
||||
[FromRoute] long id,
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -170,8 +170,8 @@ namespace xIds.Controllers
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpPut("ApiKeys/Usages/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPut("Applications/ApiKeys/Usages/{id}")]
|
||||
public async Task<ActionResult<XApiKeyUsageDto>> UpdateApiKeyUsage(
|
||||
[FromRoute] long id,
|
||||
[FromBody] XApiKeyUsageDto item,
|
||||
@@ -219,8 +219,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("ApiKeys/Usages")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/ApiKeys/Usages")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<IEnumerable<XApiKeyUsageDto>>> GetAllApiKeyUsages(
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -260,7 +260,7 @@ namespace xIds.Controllers
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/ApiKeys/Usages/Query")]
|
||||
[HttpGet("ApiKeys/Usages/Query")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XQueryResult<XApiKeyUsageDto>>> QueryApiKeyUsages(
|
||||
[FromRoute] XQuery query,
|
||||
|
||||
@@ -36,8 +36,8 @@ namespace xIds.Controllers
|
||||
/// <param name="item"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("")]
|
||||
[RequireXPowered]
|
||||
[HttpPost("Applications")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApplicationDto>> CreateApplication(
|
||||
@@ -93,8 +93,8 @@ namespace xIds.Controllers
|
||||
/// <param name="item"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPut("")]
|
||||
[RequireXPowered]
|
||||
[HttpPut("Applications")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApplicationDto>> UpdateApplication(
|
||||
@@ -141,8 +141,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpDelete("Applications/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApplicationDto>> RemoveApplication(
|
||||
[FromRoute] int id,
|
||||
@@ -188,8 +188,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("{id}")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/{id}")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XApplicationDto>> GetApplication(
|
||||
[FromRoute] int id,
|
||||
@@ -234,9 +234,9 @@ namespace xIds.Controllers
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet("")]
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<IEnumerable<XApplicationDto>>> GetAllApplications(
|
||||
CancellationToken cancellationToken = default
|
||||
@@ -275,8 +275,8 @@ namespace xIds.Controllers
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpGet("Query")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("Applications/Query")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
public async Task<ActionResult<XQueryResult<XApplicationDto>>> QueryApplications(
|
||||
[FromRoute] XQuery query,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xIdentityHelper;
|
||||
using System.Threading;
|
||||
using xCommons.Attributes;
|
||||
@@ -17,10 +18,68 @@ namespace xIds.Controllers
|
||||
{
|
||||
public partial class ApplicationsController
|
||||
{
|
||||
/// <summary>
|
||||
/// Show Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys/Create")]
|
||||
[HttpGet("{applicationId}/ApiKeys/{apiKeyId}/Show")]
|
||||
public async Task<ActionResult<string>> ShowApiKey(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (
|
||||
apiKeyId.IsDefaultGuid() ||
|
||||
!applicationId.IsValidIntId())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await provider.ShowApiKey(
|
||||
userInfo: userInfo,
|
||||
apiKeyId: apiKeyId,
|
||||
applicationId: applicationId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("{applicationId}/ApiKeys/Create")]
|
||||
public async Task<ActionResult<XApiKeyDto>> CreateApiKey(
|
||||
[FromRoute] int applicationId,
|
||||
[FromBody] XCreateApiKeyRequest request,
|
||||
@@ -56,14 +115,34 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
//
|
||||
// Create Specified Api Key ...
|
||||
// Noramlize TimeSpan ...
|
||||
var expirationTimeSpan = TimeSpan
|
||||
.FromMinutes(apiKeyConfiguration.DefaultExpirationMinutes);
|
||||
if (
|
||||
request.ExpirationMinutes.HasValue &&
|
||||
request.ExpirationMinutes.Value > 0
|
||||
)
|
||||
{
|
||||
//
|
||||
// Normalize Expiration Minutes ...
|
||||
int minutes = request.ExpirationMinutes.Value;
|
||||
if (minutes > apiKeyConfiguration.MaxExpirationMinutes)
|
||||
{
|
||||
minutes = apiKeyConfiguration.MaxExpirationMinutes;
|
||||
}
|
||||
|
||||
//
|
||||
expirationTimeSpan = TimeSpan.FromMinutes(minutes);
|
||||
}
|
||||
|
||||
//
|
||||
var result = await provider.CreateApiKey(
|
||||
userInfo: userInfo,
|
||||
scopes: request.Scopes,
|
||||
applicationId: applicationId,
|
||||
rateLimit: request.RateLimit,
|
||||
allowedIPs: request.AllowedIPs,
|
||||
expiration: request.Expiration,
|
||||
expiration: expirationTimeSpan,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
@@ -78,10 +157,17 @@ namespace xIds.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Remove Specified Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpDelete("Applications/{applicationId}/ApiKeys/{apiKeyId}")]
|
||||
[HttpDelete("{applicationId}/ApiKeys/{apiKeyId}")]
|
||||
public async Task<ActionResult<XApiKeyDto>> RemoveApiKey(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
@@ -117,7 +203,6 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
//
|
||||
// Create Specified Api Key ...
|
||||
var result = await provider.RemoveApiKeyAsync(
|
||||
id: apiKeyId,
|
||||
softDelete: false,
|
||||
@@ -136,10 +221,18 @@ namespace xIds.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rotate Specified Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}")]
|
||||
[HttpPost("{applicationId}/ApiKeys/{apiKeyId}")]
|
||||
public async Task<ActionResult<XApiKeyDto>> RotateApiKey(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
@@ -192,7 +285,6 @@ namespace xIds.Controllers
|
||||
}
|
||||
|
||||
//
|
||||
// Create Specified Api Key ...
|
||||
var result = await provider.RotateApiKey(
|
||||
apiKeyId: apiKeyId,
|
||||
userInfo: userInfo,
|
||||
@@ -211,55 +303,254 @@ namespace xIds.Controllers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Revoke Specified Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}/Revoke")]
|
||||
public async Task<ActionResult<XApiKeyDto>> RevokeApiKey(
|
||||
[HttpPost("{applicationId}/ApiKeys/{apiKeyId}/Revoke")]
|
||||
public async Task<ActionResult<bool>> RevokeApiKey(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (
|
||||
apiKeyId.IsDefaultGuid() ||
|
||||
!applicationId.IsValidIntId())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
// Retrieve Application for Validating ...
|
||||
var application = await provider.GetApplicationAsync(
|
||||
id: applicationId,
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true
|
||||
);
|
||||
if (application.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = await provider.RevokeApiKey(
|
||||
apiKeyId: apiKeyId,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Specified Application's Api Keys ...
|
||||
/// </summary>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpGet("{applicationId}/ApiKeys")]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys")]
|
||||
public async Task<ActionResult<IEnumerable<XApiKeyDto>>> GetApiKeys(
|
||||
[FromRoute] int applicationId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (!applicationId.IsValidIntId())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
// Retrieve Application for Validating ...
|
||||
var application = await provider.GetApplicationAsync(
|
||||
id: applicationId,
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true
|
||||
);
|
||||
if (application.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = await provider.GetApplicationApiKeys(
|
||||
userInfo: userInfo,
|
||||
applicationId: applicationId,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result.ToDynamicObject());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve Specified Api Keys Usages ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[Authorize(Policy = XPolicies.EnabledUser)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}/Usages")]
|
||||
public async Task<ActionResult<XApiKeyDto>> GetApiKeyUsages(
|
||||
[HttpGet("{applicationId}/ApiKeys/{apiKeyId}/Usages")]
|
||||
public async Task<ActionResult<IEnumerable<XApiKeyUsageDto>>> GetApiKeyUsages(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
[RequireXPowered]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
[HttpPost("Applications/{applicationId}/ApiKeys/{apiKeyId}/Validate")]
|
||||
public async Task<ActionResult<XApiKeyDto>> ValidateApiKey(
|
||||
[FromRoute] Guid apiKeyId,
|
||||
[FromRoute] int applicationId,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (
|
||||
apiKeyId.IsDefaultGuid() ||
|
||||
!applicationId.IsValidIntId())
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
// Retrieve Application for Validating ...
|
||||
var application = await provider.GetApplicationAsync(
|
||||
id: applicationId,
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true
|
||||
);
|
||||
if (application.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve ApiKey for Validating ...
|
||||
var apiKey = await provider.GetApiKeyAsync(
|
||||
id: apiKeyId,
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true
|
||||
);
|
||||
if (application.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
var result = await provider.FindManyApiKeyUsageAsync(
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true,
|
||||
cancellationToken: cancellationToken,
|
||||
predicate: x => x.ApiKeyId == apiKeyId,
|
||||
orderBuilder: x => x.OrderBy(y => y.RequestedOn)
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result.ToDynamicObject());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validate Specifed Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="request"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[RequireXPowered]
|
||||
[HttpPost("ApiKeys/Validate")]
|
||||
[Authorize(LocalApi.PolicyName)]
|
||||
public async Task<ActionResult<XApiKeyValidationResult>> ValidateApiKey(
|
||||
[FromBody] XApiKeyValidationRequest request,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
await ValidationProvider
|
||||
.GroupValidationBuilder()
|
||||
.AddNotNull(request)
|
||||
.AddNotEmpty(request.ApiKey)
|
||||
.AddNotEmpty(request.ClientIP)
|
||||
.ValidateGroupAsync();
|
||||
|
||||
//
|
||||
var userInfo = await GetUserInfo();
|
||||
|
||||
//
|
||||
var result = await provider.ValidateApiKey(
|
||||
userInfo: userInfo,
|
||||
apiKey: request.ApiKey,
|
||||
clientIP: request.ClientIP,
|
||||
requiredScope: request.RequiredScope,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
|
||||
//
|
||||
return Ok(result.ToDynamicObject());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
//
|
||||
var result = GetExceptionActionResult(ex);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
-21
@@ -204,7 +204,7 @@ namespace xIds.DI
|
||||
{
|
||||
//
|
||||
source.AddXApiKeyConfiguration(configuration);
|
||||
|
||||
|
||||
//
|
||||
source.AddMemoryCache();
|
||||
source.AddScoped<IXApplicationProvider, XApplicationProvider>();
|
||||
@@ -399,41 +399,67 @@ namespace xIds.DI
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <param name="configuration"></param>
|
||||
/// <param name="addApiKeyAuthentication"></param>
|
||||
public static void AddXIdentityServerAuthentication(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration,
|
||||
bool addApiKeyAuthentication = false
|
||||
IConfiguration configuration
|
||||
)
|
||||
{
|
||||
//
|
||||
// Adding Requirements ...
|
||||
services.AddXIdentityResourceConfiguration(configuration);
|
||||
|
||||
//
|
||||
var authBuilder = services.AddAuthentication();
|
||||
|
||||
//
|
||||
// Add JWT Bearer ...
|
||||
// Create Authentication Builder ...
|
||||
// var authBuilder = services.AddAuthentication();
|
||||
|
||||
//
|
||||
// Create Authentication Builder ...
|
||||
var authBuilder = services.AddAuthentication(options =>
|
||||
{
|
||||
//
|
||||
// Setting Default Authentication Schema ...
|
||||
// For Handling Smart Schema Forwarder ...
|
||||
options.DefaultScheme = XAuthentication.SMART_SCHEME;
|
||||
options.DefaultChallengeScheme = XAuthentication.SMART_SCHEME;
|
||||
options.DefaultAuthenticateScheme = XAuthentication.SMART_SCHEME;
|
||||
})
|
||||
.AddPolicyScheme(
|
||||
authenticationScheme: XAuthentication.SMART_SCHEME,
|
||||
displayName: XAuthentication.SMART_SCHEME,
|
||||
configureOptions: options =>
|
||||
{
|
||||
//
|
||||
// Configure Forward Default Selector ...
|
||||
options.ForwardDefaultSelector = context =>
|
||||
{
|
||||
//
|
||||
// Retrieve XApiKey Header Key ...
|
||||
var apiKeyHeader = XHeader.ApiKey.GetStringValue();
|
||||
|
||||
//
|
||||
// If Header Contains Key ...
|
||||
if (context.Request.Headers.ContainsKey(apiKeyHeader))
|
||||
{
|
||||
return XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
}
|
||||
|
||||
//
|
||||
// If not ...
|
||||
return XAuthentication.IDENTITY_SERVER_LOCAL_API;
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
//
|
||||
// Add JwtBearer by Smart Schema ForwardDefaultSelector ...
|
||||
authBuilder.AddJwtBearer(options =>
|
||||
{
|
||||
//
|
||||
options.SaveToken = true;
|
||||
options.RequireHttpsMetadata = false;
|
||||
|
||||
//
|
||||
options.ForwardDefault = XAuthentication.IDENTITY_SERVER_LOCAL_API;
|
||||
})
|
||||
.AddLocalApi();
|
||||
|
||||
//
|
||||
if (addApiKeyAuthentication)
|
||||
{
|
||||
//
|
||||
authBuilder.AddScheme<AuthenticationSchemeOptions, XApiKeyAuthenticationHandler>(
|
||||
XAuthenticationScheme.XApiKey.GetStringValue(),
|
||||
options => {}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -485,7 +511,13 @@ namespace xIds.DI
|
||||
options.AddPolicy(IdentityServerConstants.LocalApi.PolicyName, policy =>
|
||||
{
|
||||
//
|
||||
policy.AddAuthenticationSchemes(IdentityServerConstants.LocalApi.AuthenticationScheme);
|
||||
policy.AddAuthenticationSchemes(
|
||||
[
|
||||
XAuthenticationScheme.XApiKey.GetStringValue(),
|
||||
IdentityServerConstants.LocalApi.AuthenticationScheme
|
||||
]);
|
||||
|
||||
//
|
||||
policy.RequireAuthenticatedUser();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Security.Cryptography;
|
||||
using xIdentityModels.Constants;
|
||||
using xIdentityHelper;
|
||||
|
||||
namespace xIds.Helpers
|
||||
{
|
||||
@@ -73,5 +75,35 @@ namespace xIds.Helpers
|
||||
var hash = ComputeHash(plainKey);
|
||||
return hash == storedHash;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve All ApiKey Scopes ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static XApiKeyScope[] GetXApiKeyScopes()
|
||||
{
|
||||
//
|
||||
return [
|
||||
XApiKeyScope.Read,
|
||||
XApiKeyScope.Write,
|
||||
XApiKeyScope.Manage,
|
||||
XApiKeyScope.Admin,
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieve All ApiKey Policies ...
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string[] GetXApiKeyPolicies()
|
||||
{
|
||||
return [
|
||||
XPolicies.ApiKeyAccess,
|
||||
XPolicies.ApiKeyReadAccess,
|
||||
XPolicies.ApiKeyWriteAccess,
|
||||
XPolicies.ApiKeyAdminAccess,
|
||||
XPolicies.ApiKeyManageAccess,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -176,11 +176,13 @@ namespace xIds.Interfaces
|
||||
/// Add Specified Item ...
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="apiKey"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<XApiKeyDto> AddApiKeyAsync(
|
||||
XApiKeyDto item,
|
||||
string apiKey = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
@@ -480,6 +482,21 @@ namespace xIds.Interfaces
|
||||
|
||||
//
|
||||
#region Custom Actions ...
|
||||
/// <summary>
|
||||
/// Show Specifid Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<string> ShowApiKey(
|
||||
Guid apiKeyId,
|
||||
int applicationId,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Generate a New ApiKey and Add It to DB ...
|
||||
/// </summary>
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
using System.Linq;
|
||||
using xIds.Helpers;
|
||||
using IdentityModel;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace xIds.Providers
|
||||
@@ -41,25 +46,61 @@ namespace xIds.Providers
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
//
|
||||
var apiKey =
|
||||
!Request.Headers.ContainsKey(HeaderName)
|
||||
? string.Empty
|
||||
: Request.Headers[HeaderName].ToString();
|
||||
if (apiKey.IsNullOrEmpty())
|
||||
// Obtain the endpoint currently being executed
|
||||
var endpoint = Context.GetEndpoint();
|
||||
|
||||
//
|
||||
// Retrieve all AuthorizeAttribute metadata from the endpoint
|
||||
var hasApiKeyScheme = false;
|
||||
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
|
||||
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
|
||||
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
|
||||
if (
|
||||
apiKeyPolicies.HasChild() &&
|
||||
authorizeAttributes.HasChild()
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve a List of ApiKey Policies ...
|
||||
hasApiKeyScheme = authorizeAttributes.Any(attr =>
|
||||
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString()) ||
|
||||
attr.AuthenticationSchemes.ToNormalString() == XAuthenticationScheme.XApiKey.GetStringValue().ToNormalString()
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// if there is not any Policies for ApiKey Authentication
|
||||
// or Authorization, pass no Result ...
|
||||
if (!hasApiKeyScheme)
|
||||
{
|
||||
return AuthenticateResult.NoResult();
|
||||
}
|
||||
|
||||
//
|
||||
var apiKeyHeader = HeaderName;
|
||||
if (!Request.Headers.ContainsKey(apiKeyHeader))
|
||||
{
|
||||
return AuthenticateResult.Fail("ApiKey not Exists ...");
|
||||
}
|
||||
|
||||
//
|
||||
var apiKey = Request.Headers[apiKeyHeader].ToString();
|
||||
if (apiKey.IsNullOrEmpty())
|
||||
{
|
||||
return AuthenticateResult.Fail("ApiKey not Provided ...");
|
||||
}
|
||||
|
||||
// Extract Client IP ...
|
||||
var clientIP = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
//
|
||||
var validationResult = await applicationProvider.ValidateApiKey(
|
||||
apiKey: apiKey,
|
||||
clientIP: clientIP
|
||||
);
|
||||
var isValid = !validationResult.Errors.HasChild();
|
||||
if (!isValid)
|
||||
// Validating ApiKey ...
|
||||
var validationResult = await applicationProvider
|
||||
.ValidateApiKey(
|
||||
apiKey: apiKey,
|
||||
clientIP: clientIP
|
||||
);
|
||||
if (validationResult.Errors.HasChild())
|
||||
{
|
||||
//
|
||||
var message = validationResult.Errors.ToListString('\n');
|
||||
@@ -67,32 +108,35 @@ namespace xIds.Providers
|
||||
}
|
||||
|
||||
//
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.Name, validationResult.OwnerId),
|
||||
new Claim("application_id", validationResult.ApplicationId.ToString()),
|
||||
new Claim("auth_type", "apikey"),
|
||||
new Claim(JwtClaimTypes.Scope, "apikey"),
|
||||
// Creating Claims ...
|
||||
var claims = new List<Claim> {
|
||||
//
|
||||
// Owner Identifier of API Key ...
|
||||
new(ClaimTypes.Name, validationResult.OwnerId),
|
||||
new(JwtClaimTypes.Subject, validationResult.OwnerId),
|
||||
//
|
||||
// Application Id ...
|
||||
new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
|
||||
//
|
||||
// Authentication Type ...
|
||||
new(XCustomClaims.AuthType, "apikey"),
|
||||
};
|
||||
|
||||
//
|
||||
var scopeClaims = validationResult.Scopes
|
||||
.Select(s => new Claim(JwtClaimTypes.Scope, s));
|
||||
|
||||
//
|
||||
var identity = new ClaimsIdentity(
|
||||
claims.Union(scopeClaims),
|
||||
AuthenticationScheme
|
||||
);
|
||||
|
||||
//
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
// Add Scopes ...
|
||||
if (validationResult.Scopes != null)
|
||||
{
|
||||
foreach (var scope in validationResult.Scopes)
|
||||
{
|
||||
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
var ticket = new AuthenticationTicket(
|
||||
principal,
|
||||
AuthenticationScheme
|
||||
);
|
||||
// Create Principal and Ticket ...
|
||||
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
|
||||
//
|
||||
return AuthenticateResult.Success(ticket);
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using xIds.Helpers;
|
||||
using IdentityModel;
|
||||
using xIds.Interfaces;
|
||||
using xIdentityHelper;
|
||||
using xCommons.Constants;
|
||||
using xCommons.Extensions;
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using xIdentityModels.Constants;
|
||||
using xIdentityService.Constants;
|
||||
using System.Collections.Generic;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
[AttributeUsage(
|
||||
AttributeTargets.Class | AttributeTargets.Method,
|
||||
AllowMultiple = false,
|
||||
Inherited = true
|
||||
)]
|
||||
public class XApiKeyAuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
|
||||
{
|
||||
// /// <summary>
|
||||
// /// Optional required scope for this endpoint.
|
||||
// /// Example: [XApiKeyAuthorizationFilter(RequiredScope = "read")]
|
||||
// /// </summary>
|
||||
// public string RequiredScope { get; set; }
|
||||
|
||||
// /// <summary>
|
||||
// /// If false, a missing header will only result in NoResult (anonymous)
|
||||
// /// instead of a 401. Default is true (must provide a key).
|
||||
// /// </summary>
|
||||
// public bool ApiKeyRequired { get; set; } = true;
|
||||
|
||||
// /// <summary>
|
||||
// /// Optional allowed scopes. If empty, no scope enforcement.
|
||||
// /// </summary>
|
||||
// public string[] AllowedScopes { get; set; }
|
||||
|
||||
public XApiKeyAuthorizationFilter() { }
|
||||
|
||||
/// <summary>
|
||||
/// Authorization Filtering ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
Task.FromResult(OnAuthorizationAsync(context));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle Authorization Filtering Using Tasks ...
|
||||
/// </summary>
|
||||
/// <param name="context"></param>
|
||||
/// <returns></returns>
|
||||
private async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
||||
{
|
||||
//
|
||||
// Access HttpContext ...
|
||||
var http = context.HttpContext;
|
||||
|
||||
//
|
||||
try
|
||||
{
|
||||
//
|
||||
// Obtain the endpoint currently being executed
|
||||
var endpoint = http.GetEndpoint();
|
||||
|
||||
//
|
||||
// Retrieve all AuthorizeAttribute metadata from the endpoint
|
||||
var hasApiKeyScheme = false;
|
||||
var apiKeyScopes = XApiKeyHelper.GetXApiKeyScopes();
|
||||
var apiKeyPolicies = XApiKeyHelper.GetXApiKeyPolicies();
|
||||
var authorizeAttributes = endpoint?.Metadata.GetOrderedMetadata<IAuthorizeData>();
|
||||
if (
|
||||
apiKeyPolicies.HasChild() &&
|
||||
authorizeAttributes.HasChild()
|
||||
)
|
||||
{
|
||||
//
|
||||
// Retrieve a List of ApiKey Policies ...
|
||||
hasApiKeyScheme = authorizeAttributes.Any(attr =>
|
||||
apiKeyPolicies.Any(asc => asc.ToNormalString() == attr.Policy.ToNormalString())
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// if there is not any Policies for ApiKey Authentication
|
||||
// or Authorization, pass no Result ...
|
||||
if (!hasApiKeyScheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve the application provider from DI ...
|
||||
var applicationProvider = http.RequestServices
|
||||
.GetService(typeof(IXApplicationProvider))
|
||||
as IXApplicationProvider;
|
||||
if (applicationProvider.IsNull())
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("Provider Service Not Registered ...");
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Checking Header ...
|
||||
var apiKeyHeader = XHeader.ApiKey.GetStringValue();
|
||||
var apiKeyAuthentication = XAuthenticationScheme.XApiKey.GetStringValue();
|
||||
if (!http.Request.Headers.ContainsKey(apiKeyHeader))
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey not Exists ...");
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Extract ApiKey from Header ...
|
||||
var apiKey = http.Request.Headers[apiKeyHeader].ToString();
|
||||
if (apiKey.IsNullOrEmpty())
|
||||
{
|
||||
//
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey not Provided ...");
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Extract Client IP ...
|
||||
var clientIP = http.Request.HttpContext.Connection.RemoteIpAddress?.ToString();
|
||||
|
||||
//
|
||||
// Validating ApiKey ...
|
||||
var validationResult = await applicationProvider
|
||||
.ValidateApiKey(
|
||||
apiKey: apiKey,
|
||||
clientIP: clientIP
|
||||
);
|
||||
if (validationResult.Errors.HasChild())
|
||||
{
|
||||
//
|
||||
var message = validationResult.Errors.ToListString('\n');
|
||||
context.Result = new UnauthorizedObjectResult(message);
|
||||
return;
|
||||
}
|
||||
|
||||
//
|
||||
// Creating Claims ...
|
||||
var claims = new List<Claim> {
|
||||
//
|
||||
// Owner Identifier of API Key ...
|
||||
new(ClaimTypes.Name, validationResult.OwnerId),
|
||||
new(JwtClaimTypes.Subject, validationResult.OwnerId),
|
||||
//
|
||||
// Application Id ...
|
||||
new(XCustomClaims.ApplicationId, validationResult.ApplicationId.ToString()),
|
||||
//
|
||||
// Authentication Type ...
|
||||
new(XCustomClaims.AuthType, apiKeyAuthentication),
|
||||
};
|
||||
|
||||
//
|
||||
// Add Scopes ...
|
||||
if (validationResult.Scopes != null)
|
||||
{
|
||||
//
|
||||
foreach (var scope in validationResult.Scopes)
|
||||
{
|
||||
claims.Add(new Claim(JwtClaimTypes.Scope, scope));
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Create Principal and Ticket ...
|
||||
var identity = new ClaimsIdentity(claims, apiKeyAuthentication);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
//
|
||||
http.User = principal;
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.Result = new UnauthorizedObjectResult("ApiKey authorization failed ...");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ using IdentityServer4.Extensions;
|
||||
using xIdentityModels.Extensions;
|
||||
using Microsoft.EntityFrameworkCore.Query;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using AutoMapper;
|
||||
|
||||
namespace xIds.Providers
|
||||
{
|
||||
@@ -28,6 +29,7 @@ namespace xIds.Providers
|
||||
private readonly IXIdentityManager identityManager;
|
||||
private readonly XDataServiceConfiguration configuration;
|
||||
private readonly XApiKeyConfiguration apiKeyConfiguration;
|
||||
private readonly Action<IMapperConfigurationExpression> mapperConfigurationExp;
|
||||
|
||||
public XApplicationProvider(
|
||||
IMemoryCache cache,
|
||||
@@ -45,6 +47,23 @@ namespace xIds.Providers
|
||||
this.configuration = configuration;
|
||||
this.identityManager = identityManager;
|
||||
this.apiKeyConfiguration = apiKeyConfiguration;
|
||||
|
||||
//
|
||||
// Configure Mapper Options ...
|
||||
mapperConfigurationExp = cfg =>
|
||||
{
|
||||
//
|
||||
cfg.CreateMap<XApiKey, XApiKeyDto>()
|
||||
.ReverseMap();
|
||||
|
||||
//
|
||||
cfg.CreateMap<XApplication, XApplicationDto>()
|
||||
.ReverseMap();
|
||||
|
||||
//
|
||||
cfg.CreateMap<XApiKeyUsage, XApiKeyUsageDto>()
|
||||
.ReverseMap();
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -288,14 +307,14 @@ namespace xIds.Providers
|
||||
/// <param name="limitPerMinute"></param>
|
||||
/// <returns></returns>
|
||||
private bool CheckRateLimit(
|
||||
Guid apiKeyId,
|
||||
Guid apiKeyId,
|
||||
int limitPerMinute
|
||||
)
|
||||
{
|
||||
//
|
||||
var cacheKey = $"ratelimit:{apiKeyId}";
|
||||
var currentCount = cache.GetOrCreate(
|
||||
cacheKey,
|
||||
cacheKey,
|
||||
entry =>
|
||||
{
|
||||
//
|
||||
@@ -305,14 +324,15 @@ namespace xIds.Providers
|
||||
);
|
||||
|
||||
//
|
||||
if (currentCount >= limitPerMinute) {
|
||||
if (currentCount >= limitPerMinute)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
//
|
||||
cache.Set(
|
||||
cacheKey,
|
||||
currentCount + 1,
|
||||
cacheKey,
|
||||
currentCount + 1,
|
||||
TimeSpan.FromMinutes(1)
|
||||
);
|
||||
|
||||
|
||||
@@ -26,11 +26,13 @@ namespace xIds.Providers
|
||||
/// Add Specified Item ...
|
||||
/// </summary>
|
||||
/// <param name="item"></param>
|
||||
/// <param name="apiKey"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<XApiKeyDto> AddApiKeyAsync(
|
||||
XApiKeyDto item,
|
||||
string apiKey = null,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
@@ -85,7 +87,12 @@ namespace xIds.Providers
|
||||
item.CreatedOn = DateTime.UtcNow;
|
||||
|
||||
//
|
||||
var entity = item.MapConvert<XApiKey, XApiKeyDto>();
|
||||
var entity = item.MapConvert<XApiKey, XApiKeyDto>(mapperConfigurationExp);
|
||||
if (!apiKey.IsNullOrEmpty())
|
||||
{
|
||||
entity.Key = apiKey;
|
||||
}
|
||||
|
||||
var entry = await dbContext.ApiKeys.AddAsync(
|
||||
entity: entity,
|
||||
cancellationToken: cancellationToken
|
||||
|
||||
@@ -17,6 +17,67 @@ namespace xIds.Providers
|
||||
{
|
||||
//
|
||||
#region Custom Actions ...
|
||||
/// <summary>
|
||||
/// Show Specifid Api Key ...
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId"></param>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="userInfo"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<string> ShowApiKey(
|
||||
Guid apiKeyId,
|
||||
int applicationId,
|
||||
XUserClaimsInfoDto userInfo = null,
|
||||
CancellationToken cancellationToken = default
|
||||
)
|
||||
{
|
||||
//
|
||||
// Validate ...
|
||||
if (
|
||||
apiKeyId.IsDefaultGuid() ||
|
||||
userInfo.IsNullOrDefault() ||
|
||||
!applicationId.IsValidIntId()
|
||||
)
|
||||
{
|
||||
XException.InvalidArgs.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Check Application Exists ...
|
||||
var application = await GetApplicationAsync(
|
||||
id: applicationId,
|
||||
userInfo: userInfo,
|
||||
includeBuilder: null,
|
||||
ignoreSoftDeleteds: true,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
if (application.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Validate Owner ...
|
||||
if (!IsOwned(application, userInfo))
|
||||
{
|
||||
XException.NotAllowed.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
// Retrieve ApiKey Entity ...
|
||||
// Since ApiKey is Only Exists on ApiKey Entity ...
|
||||
var entity = await dbContext.ApiKeys
|
||||
.FirstOrDefaultAsync(x => x.Id == apiKeyId);
|
||||
if (entity.IsNullOrDefault())
|
||||
{
|
||||
XException.NotFound.Throw();
|
||||
}
|
||||
|
||||
//
|
||||
return entity.Key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate a New ApiKey and Add It to DB ...
|
||||
/// </summary>
|
||||
@@ -114,6 +175,7 @@ namespace xIds.Providers
|
||||
// Add Item to Database ...
|
||||
result = await AddApiKeyAsync(
|
||||
item: result,
|
||||
apiKey: plainKey,
|
||||
userInfo: userInfo,
|
||||
cancellationToken: cancellationToken
|
||||
);
|
||||
@@ -371,8 +433,8 @@ namespace xIds.Providers
|
||||
.ParseListString<string>();
|
||||
var allowedScopes = (keyModel.AllowedScopes ?? string.Empty)
|
||||
.FromJSON<IEnumerable<string>>();
|
||||
result.Scopes = [..allowedScopes];
|
||||
|
||||
result.Scopes = [.. allowedScopes];
|
||||
|
||||
//
|
||||
// Check Application is Exists and Active ...
|
||||
var application = await dbContext.Applications
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace xIds.Providers
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = source.MapConvert<XApiKeyDto, XApiKey>();
|
||||
var result = source.MapConvert<XApiKeyDto, XApiKey>(mapperConfigurationExp);
|
||||
result = await EnrichAsync(
|
||||
source: result,
|
||||
cancellationToken: cancellationToken
|
||||
@@ -88,7 +88,7 @@ namespace xIds.Providers
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = source.MapConvert<XApiKeyUsageDto, XApiKeyUsage>();
|
||||
var result = source.MapConvert<XApiKeyUsageDto, XApiKeyUsage>(mapperConfigurationExp);
|
||||
result = await EnrichAsync(
|
||||
source: result,
|
||||
cancellationToken: cancellationToken
|
||||
@@ -110,7 +110,7 @@ namespace xIds.Providers
|
||||
)
|
||||
{
|
||||
//
|
||||
var result = source.MapConvert<XApplicationDto, XApplication>();
|
||||
var result = source.MapConvert<XApplicationDto, XApplication>(mapperConfigurationExp);
|
||||
result = await EnrichAsync(
|
||||
source: result,
|
||||
cancellationToken: cancellationToken
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
using System;
|
||||
using xIds.Interfaces;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using System.Threading.Tasks;
|
||||
using IdentityServer4.Events;
|
||||
using IdentityServer4.Models;
|
||||
using IdentityServer4.Services;
|
||||
using IdentityServer4.Validation;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using xCommons.Extensions;
|
||||
using xExceptions.Constants;
|
||||
using xIdentityModels.Navigations;
|
||||
using xIds.Interfaces;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static IdentityModel.OidcConstants;
|
||||
|
||||
namespace xIds.Validators
|
||||
|
||||
@@ -37,12 +37,12 @@
|
||||
"MaxFileSize": 41943040
|
||||
},
|
||||
"ApiKeyConfiguration": {
|
||||
"ApiPrefix": "xapp",
|
||||
"ApiKeyPrefix": "xapp",
|
||||
"DefaultRateLimit": 60,
|
||||
"EnableAuditLog": false,
|
||||
"MaxKeysPerApplication": "10",
|
||||
"MaxExpirationMinutes": "525600",
|
||||
"DefaultExpirationMinutes": "43200"
|
||||
"MaxKeysPerApplication": 10,
|
||||
"MaxExpirationMinutes": 525600,
|
||||
"DefaultExpirationMinutes": 43200
|
||||
},
|
||||
"DbSeeder": {
|
||||
"UpdateExists": false,
|
||||
|
||||
+4
-2
@@ -29,13 +29,15 @@
|
||||
|
||||
<!-- Local Dependencies -->
|
||||
<ItemGroup>
|
||||
<PackageReference Include="xDashboard.xMessageService" Version="1.0.0" />
|
||||
<PackageReference Include="xDashboard.xStorageService" Version="1.0.0" />
|
||||
<!-- <PackageReference Include="xDashboard.xMessageService" Version="1.0.0" />
|
||||
<PackageReference Include="xDashboard.xStorageService" Version="1.0.0" /> -->
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Project Dependencies -->
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Modules\xIdentityHelper\xIdentityHelper.csproj" />
|
||||
<ProjectReference Include="..\Modules\xMessageService\xMessageService.csproj" />
|
||||
<ProjectReference Include="..\Modules\xStorageService\xStorageService.csproj" />
|
||||
<ProjectReference Include="..\Modules\xIdentityService\xIdentityService.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user