我正在打造宽度为asp.net的核心,并希望为授权设置两个登录路径:'/ account / login'为用户和'/ Admin / Account / Login'为管理员,'Admin'是一个区域名称,但不知道什么是错的宽度我。 这是我在startup.cs中的代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization();
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "UserAuthScheme",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName = ".AUTOUSERAUTHCOOKIE",
LoginPath = "/Account/Login",
CookieHttpOnly = true
});
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "AdministratorAuthScheme",
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookieName = ".AUTOADMINAUTHCOOKIE",
LoginPath = "/Admin/Account/Login",
CookieHttpOnly = true
});
...
}
AdministratorController.cs:
[Authorize(Roles ="Super",ActiveAuthenticationSchemes ="AdministratorAuthScheme")]
public async Task<IActionResult> Edit(string id)
{
if (string.IsNullOrEmpty(id))
{
return new EmptyResult();
}
.....
}
当用户没有“超级”角色时,它只会跳转到“/ Account / AccessDenied?ReturnUrl =%2FAdmin%2FAdministrator%2FEdit”。
角色:用户是普通用户,“Admin”是管理员,“super”是超级管理员,可以修改或创建管理员。 任何人都可以帮助我或提供参考链接吗? 我很抱歉我的英语很差:)。
答案 0 :(得分:1)
使用OnApplyRedirect
操作来自定义逻辑。
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)),
OnApplyRedirect = ctx =>
{
if (ctx.Request.Path.StartsWithSegments(new PathString("/admin")))
ctx.Response.Redirect("/admin/account/login?ReturnUrl=" + HttpUtility.UrlEncode(ctx.Request.Path.ToString()));
else
ctx.Response.Redirect(ctx.RedirectUri);
}
},
});
答案 1 :(得分:0)
我不认为你可以用这种方式做到这一点,最好的方法是做自定义授权属性,然后检查角色或网址并根据需要重定向用户
示例
public class CustomAuthorizeAttribute : ControllerAttribute, IAsyncActionFilter
{
public bool IsAdmin { get; set; } = false;
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var resultContext = await next();
bool hasAllowAnonymous = resultContext.ActionDescriptor.EndpointMetadata.Any(em => em.GetType() == typeof(AllowAnonymousAttribute));
bool isAuth = resultContext.HttpContext.User.Identity.IsAuthenticated;
if (!isAuth && !hasAllowAnonymous)
{
string redirectUrl = resultContext.HttpContext.Request.Path.Value;
if (IsAdmin)
resultContext.Result = new RedirectToActionResult("Index", "About", new { redirectUrl = redirectUrl, area = "Admin" });
else
resultContext.Result = new RedirectToActionResult("App", "Home", new { redirectUrl = redirectUrl });
}
}
}