Home > Software design >  Blazor: Custom AuthenticationStateProvider never returns authorised state
Blazor: Custom AuthenticationStateProvider never returns authorised state

Time:10-31

I've got a very basic blazor project setup to test authorisation via custom authentication mechanism by implementing AuthenticationStateProvider.

I've faked the authorisation state to always return a faked logged in user and added @attribute [Authorized] to my routable page component but it always shows a "Not Authorised" message when navigated to.

Started by adding the necessary initialisation in Startup.cs

 app.UseAuthentication();
 app.UseAuthorization();

I've implemented a custom AuthenticationStateProvider that always returns a logged in user:

public class LocalStorageAuthenticationStateProvider : AuthenticationStateProvider
{

        public override Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Email, "[email protected]","apiauth_type_email")
            });
    
            var user = new ClaimsPrincipal(identity);

            return Task.FromResult(new AuthenticationState(user));
        }
 }

..and I've registered my custom provider:

    services.AddScoped<AuthenticationStateProvider, LocalStorageAuthenticationStateProvider>();

..and I've added AuthorizeRouteView to App.razor

<CascadingAuthenticationState>
    <Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
        <Found Context="routeData">
            <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        </Found>
        <NotFound>
            <LayoutView Layout="@typeof(MainLayout)">
                <p>Sorry, there's nothing at this address.</p>
            </LayoutView>
        </NotFound>
    </Router>
</CascadingAuthenticationState>

Finally, I've added the authorised attribute to my routable page:

@page "/personal/dashboard"
@attribute [Authorize]

but when I navigate there, I'm always met with "Not authorised" message. What am I missing here?

CodePudding user response:

Your problem is here:

var identity = new ClaimsIdentity(new[]
{
      new Claim(ClaimTypes.Email, "[email protected]","apiauth_type_email")
});

You have typos and are not providing an authenticationType for ClaimsIdentity. Your code should look like:

var identity = new ClaimsIdentity(new[]
  {
     new Claim(ClaimTypes.Email, "[email protected]")
  }, "apiauth_type_email");
  • Related