0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-03-10 22:22:45 -05:00

feat(console): add .NET Blzor WASM tutorial (#5377)

* feat(console): add .NET Blzor WASM tutorial

* chore: fix typo
This commit is contained in:
Gao Sun 2024-02-05 22:51:07 +08:00 committed by GitHub
parent 04ec78a917
commit 715dba2ce2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 253 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
"@logto/console": minor
---
add .NET Core Blazor WASM guide

View file

@ -17,6 +17,7 @@ import thirdPartyOidc from './third-party-oidc/index';
import { type Guide } from './types';
import webDotnetCore from './web-dotnet-core/index';
import webDotnetCoreBlazorServer from './web-dotnet-core-blazor-server/index';
import webDotnetCoreBlazorWasm from './web-dotnet-core-blazor-wasm/index';
import webDotnetCoreMvc from './web-dotnet-core-mvc/index';
import webExpress from './web-express/index';
import webGo from './web-go/index';
@ -170,6 +171,13 @@ const guides: Readonly<Guide[]> = Object.freeze([
Component: lazy(async () => import('./web-dotnet-core-blazor-server/README.mdx')),
metadata: webDotnetCoreBlazorServer,
},
{
order: 5.3,
id: 'web-dotnet-core-blazor-wasm',
Logo: lazy(async () => import('./web-dotnet-core-blazor-wasm/logo.svg')),
Component: lazy(async () => import('./web-dotnet-core-blazor-wasm/README.mdx')),
metadata: webDotnetCoreBlazorWasm,
},
{
order: 6,
id: 'web-outline',

View file

@ -0,0 +1,216 @@
import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
<Steps>
<Step title="Get started">
This tutorial will show you how to use [Blorc.OpenIdConnect](https://github.com/WildGums/Blorc.OpenIdConnect) to add Logto authentication to a Blazor WebAssembly application.
<ul>
<li>It assumes your website is hosted on <code>{props.sampleUrls.origin}</code>.</li>
</ul>
### Installation
```bash
dotnet add package Blorc.OpenIdConnect
```
</Step>
<Step title="Add Blorc.OpenIdConnect to the project">
### Add script references
Include `Blorc.Core/injector.js` the `index.html` file:
```html
<head>
<!-- ... -->
<script src="_content/Blorc.Core/injector.js"></script>
<!-- ... -->
</head>
```
### Register services
Add the following code to the `Program.cs` file:
```csharp
using Blorc.OpenIdConnect;
using Blorc.Services;
builder.Services.AddBlorcCore();
builder.Services.AddAuthorizationCore();
builder.Services.AddBlorcOpenIdConnect(
options =>
{
builder.Configuration.Bind("IdentityServer", options);
});
var webAssemblyHost = builder.Build();
await webAssemblyHost
.ConfigureDocumentAsync(async documentService =>
{
await documentService.InjectBlorcCoreJsAsync();
await documentService.InjectOpenIdConnectAsync();
});
await webAssemblyHost.RunAsync();
```
Note: There's no need to use the `Microsoft.AspNetCore.Components.WebAssembly.Authentication` package. The `Blorc.OpenIdConnect` package will take care of the authentication process.
</Step>
<Step title="Configure Logto">
### Configure redirect URI
<p>
First, let's enter your redirect URI. E.g. <code>{props.sampleUrls.origin + 'Callback'}</code> (replace the endpoint with yours). This is where Logto will redirect users after they sign in.
</p>
<UriInputField name="redirectUris" />
### Configure post sign-out redirect URI
To clean up both ASP.NET session and Logto session, we can designate a post sign-out redierct URI. This is where Logto will redirect users after they sign out.
<p>
For example, set the URI to <code>{props.sampleUrls.origin + 'SignedOutCallback'}</code> (replace the endpoint with yours):
</p>
<UriInputField name="postLogoutRedirectUris" />
### Configure application
Add the following code to the `appsettings.json` file:
<pre>
<code className="language-json5">
{`// ...
IdentityServer: {
Authority: '${props.endpoint}oidc',
ClientId: '${props.app.id}',
RedirectUri: '${props.redirectUris[0] ?? props.sampleUrls.callback}',
PostLogoutRedirectUri: '${props.postLogoutRedirectUris[0] ?? props.sampleUrls.origin}',
ResponseType: 'code',
Scope: 'openid profile', // Add more scopes if needed
},
}
`}
</code>
</pre>
</Step>
<Step title="Sign-in and sign-out">
### Add `AuthorizeView` component
In the Razor pages that require authentication, add the `AuthorizeView` component. Let's assume it's the `Home.razor` page:
```cshtml
@using Microsoft.AspNetCore.Components.Authorization
@page "/"
<AuthorizeView>
<Authorized>
@* Signed in view *@
<button @onclick="OnLogoutButtonClickAsync">
Sign out
</button>
</Authorized>
<NotAuthorized>
@* Unauthenticated view *@
<button @onclick="OnLoginButtonClickAsync">
Sign in
</button>
</NotAuthorized>
</AuthorizeView>
```
### Set up authentication
In the `Home.razor.cs` file (create it if it doesn't exist), add the following code:
```csharp
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Blorc.OpenIdConnect;
using Microsoft.AspNetCore.Components.Authorization;
[Authorize]
public partial class Home : ComponentBase
{
[Inject]
public required IUserManager UserManager { get; set; }
public User<Profile>? User { get; set; }
[CascadingParameter]
protected Task<AuthenticationState>? AuthenticationStateTask { get; set; }
protected override async Task OnInitializedAsync()
{
User = await UserManager.GetUserAsync<User<Profile>>(AuthenticationStateTask!);
}
private async Task OnLoginButtonClickAsync(MouseEventArgs obj)
{
await UserManager.SignInRedirectAsync();
}
private async Task OnLogoutButtonClickAsync(MouseEventArgs obj)
{
await UserManager.SignOutRedirectAsync();
}
}
```
Once the user is authenticated, the `User` property will be populated with the user information.
### Display user information
Here are some examples of how to display user information in the `Home.razor` page:
```cshtml
<AuthorizeView>
<Authorized>
@* Signed in view *@
@* ... *@
<p>You are signed in as @(@User?.Profile?.Name ?? "(unknown name)").</p>
</Authorized>
@* ... *@
</AuthorizeView>
```
For more properties and claims, check the `User` and `Profile` classes in the `Blorc.OpenIdConnect` package.
</Step>
<Step title="Checkpoint: Test your application">
Now you can run the web application and try to sign in and sign out with Logto:
1. Open the web application in your browser, you should see "Is authenticated: False" and the "Sign in" button.
2. Click the "Sign in" button, and you should be redirected to the Logto sign-in page.
3. After you have signed in, you should be redirected back to the web application, and you should see "Is authenticated: True" and the "Sign out" button.
4. Click the "Sign out" button, and you should be redirected to the Logto sign-out page, and then redirected back to the web application.
</Step>
<Step title="The user object">
To get the user profile, you can use the `User?.Profile` property; to fetch the access token, you can use the `User?.AccessToken` property or add it to your HTTP client using `.AddAccessToken()`.
See the [full tutorial](https://docs.logto.io/sdk/dotnet-core/blazor-wasm/) for more details.
</Step>
</Steps>

View file

@ -0,0 +1,3 @@
{
"order": 5.3
}

View file

@ -0,0 +1,15 @@
import { ApplicationType } from '@logto/schemas';
import { type GuideMetadata } from '../types';
const metadata: Readonly<GuideMetadata> = Object.freeze({
name: '.NET Core (Blazor WASM)',
description: 'Integrate Logto into your .NET Core Blazor WebAssembly app.',
target: ApplicationType.SPA,
sample: {
repo: 'csharp',
path: '/',
},
});
export default metadata;

View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 1000 1000" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" xmlns:xlink="http://www.w3.org/1999/xlink">
<g><path style="opacity:0.991" fill="#5b2d91" d="M 999.5,224.5 C 999.5,247.5 999.5,270.5 999.5,293.5C 987.105,443.45 926.105,569.617 816.5,672C 683.561,790.753 527.894,841.086 349.5,823C 270.074,808.831 208.241,768.331 164,701.5C 125.156,635.721 118.49,566.721 144,494.5C 175.867,414.302 233.367,362.469 316.5,339C 413.785,318.432 496.285,344.266 564,416.5C 609.201,469.44 629.201,530.773 624,600.5C 621.636,620.75 612.469,636.917 596.5,649C 577.395,658.77 558.395,658.437 539.5,648C 525.633,638.124 517.466,624.624 515,607.5C 513.716,563.856 513.049,520.19 513,476.5C 507.273,447.106 489.773,429.273 460.5,423C 422.5,422.333 384.5,422.333 346.5,423C 283.864,433.306 241.364,468.139 219,527.5C 201.587,593.253 218.421,648.42 269.5,693C 321.584,731.019 376.584,735.686 434.5,707C 451.112,697.225 465.779,685.058 478.5,670.5C 495.368,696.172 519.035,711.672 549.5,717C 607.554,723.889 648.721,700.722 673,647.5C 684.436,618.479 688.103,588.479 684,557.5C 672.278,445.129 617.778,360.963 520.5,305C 430.417,259.489 339.084,256.822 246.5,297C 160.387,339.124 103.887,406.291 77,498.5C 51.6188,604.965 74.2855,699.632 145,782.5C 201.202,842.351 270.369,876.851 352.5,886C 503.388,899.11 642.721,865.443 770.5,785C 772.345,783.872 774.345,783.372 776.5,783.5C 776.657,784.873 776.49,786.207 776,787.5C 679.835,888.483 561.668,942.983 421.5,951C 348.701,958.22 278.701,947.553 211.5,919C 102.973,866.45 35.1393,781.283 8,663.5C 4.0882,644.511 1.25487,625.511 -0.5,606.5C -0.5,587.5 -0.5,568.5 -0.5,549.5C 12.4764,422.139 72.4764,323.972 179.5,255C 231.04,224.599 286.707,207.266 346.5,203C 397.833,202.667 449.167,202.333 500.5,202C 591.917,196.616 668.584,160.616 730.5,94C 735.357,92.2472 738.357,93.7472 739.5,98.5C 733.96,152.291 716.793,201.958 688,247.5C 686.835,250.814 688.002,252.814 691.5,253.5C 745.424,240.368 794.091,216.868 837.5,183C 868.397,156.65 894.231,126.15 915,91.5C 923.707,76.584 932.541,61.7507 941.5,47C 945.274,45.8175 948.441,46.6508 951,49.5C 979.811,104.421 995.978,162.754 999.5,224.5 Z"/></g>
<g><path style="opacity:0.991" fill="#5b2d91" d="M 348.5,482.5 C 382.835,482.333 417.168,482.5 451.5,483C 452.701,483.903 453.535,485.069 454,486.5C 454.667,518.167 454.667,549.833 454,581.5C 449.301,618.529 429.801,644.363 395.5,659C 350.606,672.59 314.106,660.757 286,623.5C 265.604,587.302 266.938,551.968 290,517.5C 305.312,498.763 324.812,487.097 348.5,482.5 Z"/></g>
</svg>

After

Width:  |  Height:  |  Size: 2.7 KiB