119 lines
3.5 KiB
C#
119 lines
3.5 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using xCommons.Extensions;
|
|
using xIdentityModels.Dtos;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http;
|
|
using xIdentityService.Attributes;
|
|
using xIdentityService.Interfaces;
|
|
using xIdentityService.Extensions;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Http.Features;
|
|
|
|
namespace xIdentityService.Middlewares
|
|
{
|
|
public class XApiKeyUsageMiddleware
|
|
{
|
|
//
|
|
#region Properties ...
|
|
private readonly RequestDelegate next;
|
|
#endregion
|
|
|
|
//
|
|
#region Constructor ...
|
|
public XApiKeyUsageMiddleware(
|
|
RequestDelegate next
|
|
)
|
|
{
|
|
this.next = next;
|
|
}
|
|
#endregion
|
|
|
|
|
|
//
|
|
#region Actions ...
|
|
public async Task InvokeAsync(
|
|
HttpContext context,
|
|
IXIdentityProvider identityProvider
|
|
)
|
|
{
|
|
//
|
|
// Check Context Has ApiKey Authorization Filter ...
|
|
var endpointFeature = context.Features.Get<IEndpointFeature>();
|
|
var endpoint =
|
|
endpointFeature.IsNull()
|
|
? null
|
|
: endpointFeature.Endpoint;
|
|
var apiKeyAccessAttibute =
|
|
endpoint.IsNull()
|
|
? null
|
|
: endpoint.Metadata.GetMetadata<XApiKeyAccessAttribute>();
|
|
if (!apiKeyAccessAttibute.IsNull())
|
|
{
|
|
//
|
|
var sw = Stopwatch.StartNew();
|
|
var requestedOn = DateTime.UtcNow;
|
|
var httpMethod = context.Request.Method;
|
|
var statusCode = StatusCodes.Status200OK;
|
|
var endpointName = context.GetRequestPath();
|
|
var clientIp = context.Request.ExtractClientIP();
|
|
|
|
//
|
|
var device = identityProvider.GetDevice();
|
|
var apiKey = context.Request.ExtractApiKey();
|
|
var cApiKeyId = context.Request.HttpContext.User.Identity;
|
|
var apiKeyId = await identityProvider.GetApiKey(
|
|
device: device,
|
|
apiKey: apiKey
|
|
);
|
|
|
|
//
|
|
try
|
|
{
|
|
await next(context);
|
|
statusCode = context.Response.StatusCode;
|
|
}
|
|
catch
|
|
{
|
|
statusCode = StatusCodes.Status500InternalServerError;
|
|
throw;
|
|
}
|
|
|
|
//
|
|
sw.Stop();
|
|
var dto = new XApiKeyUsageDto
|
|
{
|
|
ApiKeyId = apiKeyId,
|
|
ClientIP = clientIp,
|
|
Endpoint = endpointName,
|
|
StatusCode = statusCode,
|
|
HttpMethod = httpMethod,
|
|
RequestedOn = requestedOn,
|
|
ResponseTimeMs = sw.ElapsedMilliseconds,
|
|
};
|
|
await identityProvider.UseApiKey(
|
|
device: device,
|
|
apiKeyUsage: dto
|
|
);
|
|
}
|
|
else
|
|
{
|
|
await next(context);
|
|
}
|
|
}
|
|
#endregion
|
|
}
|
|
|
|
public static class XApiKeyUsageMiddlewareDIExtensions
|
|
{
|
|
/// <summary>
|
|
/// Adding XProxy Middleware to Applications ...
|
|
/// </summary>
|
|
/// <param name="app"></param>
|
|
public static void UseXApiKeyUsage(this IApplicationBuilder app)
|
|
{
|
|
app.UseMiddleware<XApiKeyUsageMiddleware>();
|
|
}
|
|
}
|
|
}
|