Ali
Ali

Reputation: 57

ASP.NET Core 2 MVC Cookie based authentication. Are there more options?

I have ASP.NET Core 2 MVC project with Cookie based authentication. Code I have attached below. Right now I don't have any problems but I am looking to improve it or any other options that I also need to explore. More Secure. I really need direction. Removed some unnecessary code.

Question:

1 - Am I doing it right. Anything to add more?

2 - Are there more options for authentication. More secure?

After Successfull Credentials

var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{

    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
    identity.AddClaim(new Claim(ClaimTypes.Email, model.Email));
    identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));

    identity.AddClaim(new Claim("Admin", "Admin"));
        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

    // Authenticate using the identity
    var principal = new ClaimsPrincipal(identity);
    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = false });

    if (Type == "Admin")
        return RedirectToAction(nameof(AdminController.Index), "Admin");

    return RedirectToAction(nameof(AccountController.Index), "Account");
}



services.AddAuthentication(options =>
{
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie();

services.AddAuthorization(options =>
{
    options.AddPolicy("admin-policy", x => { x.RequireClaim("Admin"); });
});

On Controller

[Authorize]
[Authorize(Policy = "admin-policy")]

Upvotes: 0

Views: 309

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239300

When it comes to a website-style application, no. Cookie auth is really the best you've got. HTTP requests are idempotent. To access a protected endpoint, the client (in this case, a web browser) must send something along with the request that either serves to authenticate or simply identify the client has having already been authenticated. That's where the cookie comes in. There's other ways this can be done, but principally, browsers don't really support those workflows.

With a different client, particularly clients where you have control over how the request is formatted, JWTs would probably be your best bet. However, again, that doesn't help you with a web browser. It does mean, though, that can go cookieless for things like AJAX or HttpClient requests, though, since, again, you can control the headers there.

Upvotes: 1

Related Questions