This commit is contained in:
2025-05-07 09:47:49 +08:00
parent dd86a5a818
commit f38c129bcd

View File

@@ -1,20 +1,12 @@
namespace Yes.Infrastructure.Authorizations using Microsoft.AspNetCore.Http.Extensions;
namespace Yes.Infrastructure.Authorizations
{ {
public static class AuthenticationExtensions public static class AuthenticationExtensions
{ {
public static IServiceCollection AddUserAuthentication(this IServiceCollection services) public static IServiceCollection AddUserAuthentication(this IServiceCollection services)
{ {
services.AddAuthentication(AuthenticationScheme.UserScheme) services.AddAuthentication(AuthenticationScheme.UserScheme)
.AddCookie(AuthenticationScheme.UserScheme, options =>
{
options.Cookie.Name = AuthenticationScheme.UserScheme;
options.LoginPath = "/admin/login";
options.LogoutPath = "/admin/logout";
options.ExpireTimeSpan = TimeSpan.FromDays(3);
options.SlidingExpiration = true;
});
services.AddAuthentication(AuthenticationScheme.UserApiScheme)
.AddCookie(AuthenticationScheme.UserScheme, options => .AddCookie(AuthenticationScheme.UserScheme, options =>
{ {
options.Cookie.Name = AuthenticationScheme.UserScheme; options.Cookie.Name = AuthenticationScheme.UserScheme;
@@ -26,10 +18,21 @@
options.Events.OnRedirectToAccessDenied = options.Events.OnRedirectToAccessDenied =
options.Events.OnRedirectToLogin = c => options.Events.OnRedirectToLogin = c =>
{ {
if(c.Request.GetDisplayUrl().Contains("/api"))
{
c.Response.ContentType = "application/json";
c.Response.StatusCode = StatusCodes.Status401Unauthorized; c.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.FromResult(Result.Error("请登录后操作!")); return Task.FromResult(Result.Error("请登录后操作!"));
}
else
{
c.Response.Redirect(c.RedirectUri);
return Task.CompletedTask;
}
}; };
}); });
return services; return services;
} }