Annotation authorize doesn't working ASP.NET CORE

Annotation authorize doesn't working ASP.NET CORE

Problem Description:

I’m making a CRM project. I need to restrict access to some pages to clients and workers. I’m using CookieAuthentication and Authorize attribute and for some reason it’s not working.

After registration of claims and cookies for user I’m trying to access this page "Master/Index" or "MasterController/Index" not sure which one is right to redirect but anyway instead of page I see this:
If Master as ControllerRoute
If MasterController as ControllerRoute

I’m 100% sure that user is not only Authorized but even has it’s role because debagger shows it in any case:
Step After If Statement
Step After If Statement

And my MasterController is:

    public class MasterController : Controller
        public IActionResult Index()
            return View();

That’s how I register user after his form sending on HttpPost page:

        private async Task RegisterNewUser(LoginModel login, string r)
            var claims = new List<Claim>() 
                new Claim(ClaimTypes.Name, login.Login),
                new Claim(ClaimTypes.Role, r)
            ClaimsIdentity claimsIdentity = new(claims, "Cookies");
            await ControllerContext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

And just to show you that I added auth in my Program.cs:

    .AddCookie(options => 
        options.LoginPath = "/Verification/Auth";
        options.LogoutPath = "/Verification/Logout";
        options.AccessDeniedPath = "/";



Btw, if I comment [Authorize] than everything works fine but that’s not what I need.

Solution – 1

The ordering of your middleware is incorrect. You need to place UseAuthentication() before UseAuthorization().

With it the way you have it, every time it hits the authorization middleware, it realizes the user is not authenticated, so redirects.
It never gets past that, as it will only get to the authentication middleware once it successfully passes through the authorization middleware. Hence you have an infinite loop resulting in your browser deciding it has had too many redirects.

See here for details.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.