Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC 6 Cookie Authentication - Authorization fails

I'm trying to create asp.net core mvc 6 app using Cookie Middleware authentication. My code compiles without errors, but even after successful login i'm not authorized user

Here's my startup.cs configuration

        app.UseCookieAuthentication(options =>
        {
            options.AuthenticationScheme = "CookieAuth";
            options.LoginPath = new PathString("/Account/Login/");
            options.AccessDeniedPath = new PathString("/Account/Login/");
            options.AutomaticAuthenticate = true;
            options.AutomaticChallenge = true;

        });

Also login action in my controller:

   public async Task<IActionResult> Login(LoginViewModel model)
    {

        User foundUser = _userManager.findUser(model.UserName, model.Password);


        if (foundUser != null)
        {
            List<Claim> userClaims = new List<Claim>
            {
                new Claim("userId", Convert.ToString(foundUser.UserID)),
                new Claim(ClaimTypes.Name, foundUser.UserName),
                new Claim(ClaimTypes.Role, Convert.ToString(foundUser.RoleID))
            };

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));
            await HttpContext.Authentication.SignInAsync("CookieAuth", principal);


            return RedirectToAction("Index", "Dashboard");
        }
        return View();
    }

And finally Dashboard/Index action

[Authorize]
public IActionResult Index()
{
    return View();
}

I put some breakpoints in login action and everything seems works fine. Cookie is also set correctly.

And now I don't know way i can't go to dashboard/index after sign in. Each time i'm redirected to /Account/Login/ due to configuration settings

What am I doing wrong ?

like image 203
Kuba Avatar asked Feb 17 '16 16:02

Kuba


People also ask

Can I use Cookie authentication without ASP NET Core Identity?

Use cookie authentication without ASP.NET Core Identity. ASP.NET Core Identity is a complete, full-featured authentication provider for creating and maintaining logins. However, a cookie-based authentication authentication provider without ASP.NET Core Identity can be used.

What is authorization in ASP NET Core MVC?

So far we have implemented the Cookie-based Authentication functionality in Asp.Net Core MVC project. But what about Authorization. Authorization means, providing access to the authenticated user to access a resource based on role. So, let's first understand how we can implement the Authorization in Asp.Net Core MVC.

What is authentication in MVC 6?

The following diagram gives an idea of Authentication when the end-user makes a call to an MVC 6 application. When the end-user makes a call to an MVC 6 application requesting a View, a response in the form of a View is returned when the action is executed.

How to implement authentication in ASP NET Core?

Let’s move to the starting point of the ASP.NET Core application file which is “Startup.cs” where we configure the setting for the application like configuring the required services and configuring the middleware services etc. So, implementing the Authentication features, first, we have to add the authentication and then use it.


1 Answers

When you construct your ClaimsIdentity in your login, you need to use a different constructor that specifies the authenticationType.

Instead of

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims));

You should do:

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims, "local"));

It is now possible to create a ClaimsIdentity that has claims, but having IsAuthenticated set to false. Actually this is the default now...

To have IsAuthenticated set to true, you need to specify an authentication type

I got this info from Dominick Baier's blog here.

There is also a great example of using the cookie middleware here, also by (the legendary) Dominick Baier / leastprivilege.

EDIT:

This answer contains more information about what should be used for the authenticationType string.

like image 62
Jamie Dunstan Avatar answered Sep 22 '22 14:09

Jamie Dunstan