繁体   English   中英

asp.netcore 设置两个登录路径

[英]asp.netcore set two login path

我正在请求宽度 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
    });
    ...
}

管理员控制器.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”。

角色:user为一般用户,“Admin”为管理员,“super”为超级管理员,可以修改或创建管理员。 任何人都可以帮助我或提供参考链接吗? 我为我糟糕的英语感到抱歉:)

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

我不认为你可以用这种方式做到这一点,最好的方法是做自定义授权属性,然后检查角色或 url 并根据需要重定向用户

例子

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