Blazor WASM is different from the server project. There's no Auth0 library for WASM,
so the generic OIDC library (Microsoft.AspNetCore.Components.WebAssembly.Authentication
)
is used instead.
Steps:
- Add a Nuget package
Microsoft.AspNetCore.Components.WebAssembly.Authentication
into the project.- The package is actually for OIDC/OAuth2 authentication, this case we use Auth0 as an OIDC provider.
- Set up OIDC authentication with
AddOidcAuthentication
and setProviderOptions
. SeeProgram.cs
for example.- Two important properties are
Authority
andClientId
. Seeappsettings.json
. - Note that
Authority
is an absolute URL, not just a domain name.
- Two important properties are
- Add an authentication helper page
/authentication/{action}
, seeAuthentication.razor
.- This is the single point to handle all authentication activities. To login, pass
login
as the action. To logout, passlogout
as the action. It's also the endpoint for callback too (/authentication/login-callback
).
- This is the single point to handle all authentication activities. To login, pass
- Add namespace
Microsoft.AspNetCore.Authorization
andMicrosoft.AspNetCore.Components.Authorization
in_Imports.razor
- Wrap
Route
component inApp.razor
withCascadingAuthenticaitonState
component (fromMicrosoft.AspNetCore.Authorization
) to allow underlying compoonents to retrieve authentication state.- Also change
RouteView
component toAuthorizeRouteView
which allows handling authorizing state and not-authorized state.
- Also change
Blazor framework has AuthorizeView
component to define views for authorized user and
unauthorized user. See the usage in Index.razor
.
Since this example is configured for Authorization Code Flow. Some pre-configuration needs
to be done on Auth0 side (setting Redirect URIs and Logout URIs -- see the original document
for guidance). However, since WASM is client side, so the authentication is PKCE flow, which
is handled by the library. To login/logout, use extension methods NavigateToLogin
and
NavigateToLogout
, see Index.razor
about how to login/logout using such methods.
In order to obtain the access token, Auth0 mandates the use of an API Audience. This means you need to set up
an API in Auth0 and create an identity for the API's audience. Subsequently, assign the audience name into
the AdditionalProviderParameters
, refer to Program.cs
for usage.
The OIDC library has IAccessTokenProvider
service with method RequestAccessToken
for retrieving the access
token. However, ID token is not exposed and may need many hooks so this example doesn't include it. See Index.razor
on how to get the access token.