简体   繁体   English

asp.netcore 设置两个登录路径

[英]asp.netcore set two login path

I'm beging width asp.net core, and want set two login path for authorization:'/account/login' for users and '/Admin/Account/Login' for administrators,that 'Admin' is an area name,but don't know what's wrong width me.我正在请求宽度 asp.net 核心,并希望为授权设置两个登录路径:'/account/login' 用户和 '/Admin/Account/Login' 管理员,'Admin' 是一个区域名称,但不要不知道宽度有什么问题。 here is my code in startup.cs:这是我在 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:管理员控制器.cs:

[Authorize(Roles ="Super",ActiveAuthenticationSchemes ="AdministratorAuthScheme")]
public async Task<IActionResult> Edit(string id)
{
    if (string.IsNullOrEmpty(id))
    {
        return new EmptyResult();
    }
    .....
}

when user does not have an "Super" role,it just jump to "/Account/AccessDenied?ReturnUrl=%2FAdmin%2FAdministrator%2FEdit".当用户没有“超级”角色时,它只是跳转到“/Account/AccessDenied?ReturnUrl=%2FAdmin%2FAdministrator%2FEdit”。

roles: user is for general user,"Admin" is for administrator,"super" is for Super Administrator which can modify or create administrator.角色:user为一般用户,“Admin”为管理员,“super”为超级管理员,可以修改或创建管理员。 Can any one help me or give a reference link?任何人都可以帮助我或提供参考链接吗? and i'm sorry for my poor english :)我为我糟糕的英语感到抱歉:)

Use OnApplyRedirect Action to customize the logic.使用OnApplyRedirect Action 自定义逻辑。

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);
        }
    },
});

i don't think so you can do that with this way, the best way is to do Custom Authorization attribute then check for role or url and redirect user as you want我不认为你可以用这种方式做到这一点,最好的方法是做自定义授权属性,然后检查角色或 url 并根据需要重定向用户

Example例子

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 });
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM