72 lines
2.6 KiB
C#
72 lines
2.6 KiB
C#
using Learn.Archives.Core.Model;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using OracleInternal.Secure.Network;
|
|
using SqlSugar.IOC;
|
|
using System;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Learn.Archives.Core.Common
|
|
{
|
|
public class BasicAuthMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly string _realm;
|
|
|
|
private Repository<Admin> baseservice;
|
|
|
|
public BasicAuthMiddleware(RequestDelegate next, string realm)
|
|
{
|
|
_next = next;
|
|
_realm = realm;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
if (!context.Request.Body.CanSeek)
|
|
context.Request.EnableBuffering(); // 允许重新读取请求体
|
|
|
|
if (context.Request.Path.StartsWithSegments("/swagger")
|
|
&& (context.Request.Path.Value?.Contains("swagger.json") ?? true))
|
|
{
|
|
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;
|
|
}
|
|
|
|
await _next(context);
|
|
}
|
|
|
|
private async Task<bool> IsAuthorized(string username, string password)
|
|
{
|
|
//if (baseservice == null)
|
|
//{
|
|
// using var scope = AppCommon.Services?.CreateScope();
|
|
// if (scope != null)
|
|
// baseservice = scope.ServiceProvider.GetService<Repository<Admin>>();
|
|
//}
|
|
//if (baseservice == null) return false;
|
|
|
|
var admin = await DbScoped.Sugar.Queryable<Admin>()
|
|
.FirstAsync(x => x.Account == username);
|
|
if (admin == null || !admin!.Enable) return false;
|
|
else if (admin.Password != password.GetMD5()) return false;
|
|
else return true;
|
|
}
|
|
}
|
|
}
|