2

I'm trying to build custom cookie authentication in my Blazor Server app.

It works as long as I use the DefaultAuthenticateScheme like this:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
    options.LoginPath = "/login";
    options.LogoutPath = "/logout";
});

Calling HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); will log me.

But I'd like to use custom AuthenticationSchemes to be able to have multiple schemes like:

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie("Attendee", options =>
{
    options.LoginPath = "/login";
    options.LogoutPath = "/logout";
}).AddCookie("Admin", options =>
{
    options.LoginPath = "/admin/login";
    options.LogoutPath = "/admin/logout";
});

Calling HttpContext.SignInAsync("Admin", new ClaimsPrincipal(claimsIdentity), authProperties); do set the cookie, but still my app tells me that I'm not authorized.

<AuthorizeView>
    <Authorized>Logged in!</Authorized>
    <NotAuthorized>NOT logged in!</NotAuthorized> <!-- This is shown -->
</AuthorizeView>

I'd like to be able to control the access with @attribute [Authorize(AuthenticationSchemes = "Admin")] or @attribute [Authorize(Roles = "Admin")] on each component.

What could I be missing?

Mads
  • 385
  • 1
  • 5
  • 18

2 Answers2

0

Your additional cookies aren't being used for authentication.

You could write your own authorization handler/middleware to do that, but by default, I think you can only use one cookie and you set it's name in this line of your code.

options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;

So, in brief, it's saying you're not authorized because it's testing the scheme CookieAuthenticationDefaults.AuthenticationScheme and not one of your additional two cookies.

Kieran Foot
  • 706
  • 5
  • 11
0

I know it's a bit late for you, but here is a link to another answer that indicates you can do what you are looking for by using a controller to help manage the routing for the multiple schemes. link

gwruck
  • 341
  • 2
  • 9