首页 文章

asp.netcore设置两个登录路径

提问于
浏览
1

我正在打造宽度为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”是超级管理员,可以修改或创建管理员 . 任何人都可以帮助我或提供参考链接吗?我很抱歉我的英语很差:)

1 回答

  • 1

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

相关问题