Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Authorize Attribute with Custom Cookie Authentication in ASP.NET Core

I have the following code in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    //Other middleware
    services.AddAuthentication(options =>
    {
        options.SignInScheme = "MyAuthenticationScheme";
    });

    services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //Other configurations.
    app.UseCookieAuthentication(options =>
    {
        options.AuthenticationScheme = "MyAuthenticationScheme";
        options.LoginPath = new PathString("/signin/");
        options.AccessDeniedPath = new PathString("/signin/");
        options.AutomaticAuthenticate = true;
    });
}

Then just for testing purposes, I have a login page where you just click a button and it posts back to itself, with this code in the controller.

SignInController.cs

public IActionResult Index()
{
    return View();
}

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Index(SignInViewModel model)
{
    List<Claim> claimList = new List<Claim>();
    claimList.Add(new Claim("Admin", "true"));
    ClaimsIdentity identity = new ClaimsIdentity(claimList);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    await HttpContext.Authentication.SignInAsync("MyAuthenticationScheme", principal);
    return RedirectToAction(nameof(HomeController.Index), "Home");
}

Here's the HomeController.cs

[Authorize]
public async Task<IActionResult> Index()
{
    return View();
}

I get 401 unauthorized. From my understanding the SignInAsync call should authenticate the user, and the the [Authorize] attribute should allow any authenticated users. If I do something like this in HomeController.cs:

ClaimsPrincipal cp = await HttpContext.Authentication.AuthenticateAsync("MyAuthenticationScheme");

I can see that cp does contain the Admin claim that I gave it earlier. I would think that meant the user was successfully authenticated. Why isn't the [Authorize] attribute working?

like image 965
rgvassar Avatar asked Mar 13 '23 19:03

rgvassar


1 Answers

I think you need to specify the authscheme in the constructor of the identity, your code should be more like this:

var authProperties = new AuthenticationProperties();
var identity = new ClaimsIdentity("MyAuthenticationScheme");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "1"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Admin"));
var principal = new ClaimsPrincipal(identity);
await HttpContext.Authentication.SignInAsync(
            "MyAuthenticationScheme", 
            claimsPrincipal, 
            authProperties);
return RedirectToAction(nameof(HomeController.Index), "Home");
like image 126
Joe Audette Avatar answered Apr 28 '23 04:04

Joe Audette