'Blazor Server cookie authentication with custom AuthenticationScheme

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kieran Foot