59 lines
2.0 KiB
C#
59 lines
2.0 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OracleInternal.Secure.Network;
|
|
using System;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace VideoAnalysisCore.Common
|
|
{
|
|
public class BasicAuthMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly string _realm;
|
|
|
|
|
|
|
|
public BasicAuthMiddleware(RequestDelegate next, string realm)
|
|
{
|
|
_next = next;
|
|
_realm = realm;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
if (context.Request.Path.StartsWithSegments("/swagger"))
|
|
{
|
|
string authHeader = context.Request.Headers["Authorization"];
|
|
if (authHeader != null && authHeader.StartsWith("Basic "))
|
|
{
|
|
var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
|
|
var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
|
|
var usernamePassword = decodedUsernamePassword.Split(':');
|
|
|
|
if (await IsAuthorized(usernamePassword[0], usernamePassword[1]))
|
|
{
|
|
await _next(context);
|
|
return;
|
|
}
|
|
}
|
|
|
|
context.Response.Headers["WWW-Authenticate"] = $"Basic realm=\"{_realm}\"";
|
|
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
|
return;
|
|
}
|
|
if (!context.Request.Method.Equals("GET", StringComparison.OrdinalIgnoreCase)
|
|
&& !context.Request.HasFormContentType)
|
|
context.Request.EnableBuffering();
|
|
await _next(context);
|
|
}
|
|
|
|
private async Task<bool> IsAuthorized(string username, string password)
|
|
{
|
|
// 在这里验证用户名和密码
|
|
return AppCommon.Config.Admin.Account == username
|
|
&& AppCommon.Config.Admin.Password == password;
|
|
}
|
|
}
|
|
}
|