Val
Val

Reputation: 1832

Custom JWT auth AND EntraID in one Blazor WASM app?

Is it possible to have the EntraID authentication AND custom JWT authentication in a Blazor WASM app and let the user choose which way to login?

When I have the EntraID approach working and then add a custom AuthenticationStateProvider implementation to store user login state, the app can't log the user in using EntraID and throws

System.InvalidCastException: Specified cast is not valid.
at Microsoft.Extensions.DependencyInjection.WebAssemblyAuthenticationServiceCollectionExtensions.<>c__11[[Microsoft.AspNetCore.Components.WebAssembly.Authentication.RemoteAuthenticationState, Microsoft.AspNetCore.Components.WebAssembly.Authentication...

My custom auth class:

public class ApiAuthStateProvider(AppStatus appStatus) : AuthenticationStateProvider
{
    private readonly AppStatus _appStatus = appStatus;

    public async override Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        return await Task.FromResult(CreateState());
    }

    public void StateChanged()
    {
        var authState = Task.FromResult(CreateState());
        NotifyAuthenticationStateChanged(authState);
    }

    private AuthenticationState CreateState()
    {
        if (!_appStatus.UserLogged)
            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
        else
        {
            var claims = new List<Claim> { new(ClaimTypes.Name, _appStatus.UserName ?? string.Empty) };
            claims.AddRange(_appStatus.UserRoles.Select(_ => new Claim(ClaimTypes.Role, _.ToString())));
            var anonymous = new ClaimsIdentity(claims, "Token");
            return new AuthenticationState(new ClaimsPrincipal(anonymous));
        }
    }
}

Is there a way to have both methods of authentication working?

Upvotes: 0

Views: 21

Answers (0)

Related Questions