Skip to content

Commit 3fa8470

Browse files
authored
[Preview 5] Customize the Blazor WASM auth user (#17926)
1 parent 9ea0835 commit 3fa8470

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

aspnetcore/security/blazor/webassembly/additional-scenarios.md

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,71 @@ The `RemoteAuthenticatorView` has one fragment that can be used per authenticati
395395
| `authentication/profile` | `<UserProfile>` |
396396
| `authentication/register` | `<Registering>` |
397397

398+
## Customize the user
399+
400+
Users bound to the app can be customized. In the following example, all authenticated users receive an `amr` claim for each of the user's authentication methods.
401+
402+
Create a class that extends the `RemoteUserAccount` class:
403+
404+
```csharp
405+
using System.Text.Json.Serialization;
406+
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
407+
408+
public class OidcAccount : RemoteUserAccount
409+
{
410+
[JsonPropertyName("amr")]
411+
public string[] AuthenticationMethod { get; set; }
412+
}
413+
```
414+
415+
Create a factory that extends `AccountClaimsPrincipalFactory<TAccount>`:
416+
417+
```csharp
418+
using System.Security.Claims;
419+
using System.Threading.Tasks;
420+
using Microsoft.AspNetCore.Components;
421+
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
422+
using Microsoft.AspNetCore.Components.WebAssembly.Authentication.Internal;
423+
424+
public class CustomAccountFactory
425+
: AccountClaimsPrincipalFactory<OidcAccount>
426+
{
427+
public AccountClaimsPrincipalFactory(NavigationManager navigationManager,
428+
IAccessTokenProviderAccessor accessor) : base(accessor)
429+
{
430+
}
431+
432+
public async override ValueTask<ClaimsPrincipal> CreateUserAsync(
433+
OidcAccount account, RemoteAuthenticationUserOptions options)
434+
{
435+
var initialUser = await base.CreateUserAsync(account, options);
436+
437+
if (initialUser.Identity.IsAuthenticated)
438+
{
439+
foreach (var value in account.AuthenticationMethod)
440+
{
441+
((ClaimsIdentity)initialUser.Identity)
442+
.AddClaim(new Claim("amr", value));
443+
}
444+
}
445+
446+
return initialUser;
447+
}
448+
}
449+
```
450+
451+
Register services to use the `CustomAccountFactory`:
452+
453+
```csharp
454+
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
455+
456+
...
457+
458+
builder.Services.AddApiAuthorization<RemoteAuthenticationState, OidcAccount>()
459+
.AddAccountClaimsPrincipalFactory<RemoteAuthenticationState, OidcAccount,
460+
CustomAccountFactory>();
461+
```
462+
398463
## Support prerendering with authentication
399464

400465
After following the guidance in one of the hosted Blazor WebAssembly app topics, use the following instructions to create an app that:

0 commit comments

Comments
 (0)