简体   繁体   中英

How to redirect to login page from AuthorizationFilter in asp net core?

When I return ForbidResult() it redirects to AccessDenied page as specified in startup. I want to do same with UnauthorizedResult() but redirect to Login page.

PS I'm not using standard Authorize attribute in controller I have my own.

Authorization Filter :

public class MyFilter : IAuthorizationFilter
{
    //

    public MyFilter()
    {
        //
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            var hasPermission= ... ;
            if (!hasPermission)
            {
                context.Result = new ForbidResult();
            }
        }
        else
        {
            context.Result = new UnauthorizedResult();
        }
    }
}

startup :

services.AddAuthentication.AddCookie(options =>
            {
               options.LoginPath = "/Accounts/Login";
                options.LogoutPath = "/Accounts/Logout";
                options.AccessDeniedPath = "/Accounts/AccessDenied";
            });

You can test with RedirectResult or context.Response.Redirect("/Accounts/Login");

public class MyFilter : IAuthorizationFilter
{
    //

    public MyFilter()
    {
        //
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            var hasPermission= ... ;
            if (!hasPermission)
            {
                context.Result = new ForbidResult();
            }
        }
        else
        {
            context.Result = new RedirectResult("/Accounts/Login");
        }
    }
}

For redirecting to login page which is configured in options.LoginPath = "/Accounts/Login"; , you could try code below:

public class MyFilter : IAuthorizationFilter
{
    //

    public MyFilter()
    {
        //
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            var hasPermission= ... ;
            if (!hasPermission)
            {
                context.Result = new ForbidResult();
            }
        }
        else
        {
            context.Result = new ChallengeResult(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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