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

refactor(console): improve dotnet guides

This commit is contained in:
Gao Sun 2024-07-04 14:27:14 +08:00
parent 8635f1b774
commit 0453f80598
No known key found for this signature in database
GPG key ID: 13EBE123E4773688
21 changed files with 253 additions and 413 deletions

View file

@ -4,6 +4,7 @@ import { compile } from '@mdx-js/mdx';
import { default as ThrowableDiagnostic } from '@parcel/diagnostic';
import { Transformer } from '@parcel/plugin';
import rehypeMdxCodeProps from 'rehype-mdx-code-props';
import remarkGfm from 'remark-gfm';
export default new Transformer({
async transform({ asset }) {
@ -16,6 +17,7 @@ export default new Transformer({
development: true,
jsx: true,
providerImportSource: '@mdx-js/react',
remarkPlugins: [remarkGfm],
rehypePlugins: [[rehypeMdxCodeProps, { tagName: 'code' }]],
});
} catch (error) {

View file

@ -1,20 +0,0 @@
Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:
```mermaid
graph LR
A(Your app) -->|1. Invoke sign-in| B(Logto)
B -->|2. Finish sign-in| A
```
1. Your app invokes the sign-in method.
2. The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
3. The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in:
1. This authentication process follows the [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html) protocol, and Logto enforces strict security measures to protect user sign-in.
2. If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.
To learn more about the rationale and benefits of redirect-based sign-in, see [Logto sign-in experience explained](https://docs.logto.io/docs/tutorials/get-started/sign-in-experience).
---

View file

@ -0,0 +1,17 @@
import RegardingRedirectBasedSignIn from './_regarding-redirect-based-sign-in.md';
Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:
```mermaid
graph LR
A(Your app) -->|1. Invoke sign-in| B(Logto)
B -->|2. Finish sign-in| A
```
1. Your app invokes the sign-in method.
2. The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
3. The user signs in and is redirected back to your app (configured as the redirect URI).
<RegardingRedirectBasedSignIn />
---

View file

@ -1,7 +1,7 @@
import InlineNotification from '@/ds-components/InlineNotification';
import UriInputField from '@/mdx-components/UriInputField';
import ExperienceOverview from './_experience-overview.md';
import ExperienceOverview from './_experience-overview.mdx';
export const defaultRedirectUri = 'io.logto://callback';

View file

@ -1,7 +1,7 @@
import InlineNotification from '@/ds-components/InlineNotification';
import UriInputField from '@/mdx-components/UriInputField';
import ExperienceOverview from './_experience-overview.md';
import ExperienceOverview from './_experience-overview.mdx';
export const defaultBaseUrl = 'http://localhost:3000/';
export const defaultRedirectUri = `${defaultBaseUrl}callback`;

View file

@ -0,0 +1,9 @@
<Details>
<summary>Regarding redirect-based sign-in</summary>
1. This authentication process follows the [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html) protocol, and Logto enforces strict security measures to protect user sign-in.
2. If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.
To learn more about the rationale and benefits of redirect-based sign-in, see [Logto sign-in experience explained](../../docs/tutorials/get-started/sign-in-experience.mdx).
</Details>

View file

@ -1,50 +1,35 @@
import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
import SignInAndSignOutFlows from '../web-dotnet-core-mvc/fragments/_sign-in-and-sign-out-flows.mdx';
import ConfigureRedirectUris from '../web-dotnet-core-mvc/fragments/_configure-redirect-uris.mdx';
import Installation from '../web-dotnet-core-mvc/fragments/_installation.md';
import AddAuthentication from '../web-dotnet-core-mvc/fragments/_add-authentication.mdx';
import DisplayUserInformation from '../web-dotnet-core-mvc/fragments/_display-user-information.md';
import Checkpoint from '../../fragments/_checkpoint.md';
<Steps>
<Step title="Get started">
<Step title="Add Logto SDK as a dependency">
This tutorial will show you how to use Logto ASP.NET Core authentication middleware to protect your web application.
<ul>
<li>It assumes your website is hosted on <code>{props.sampleUrls.origin}</code>.</li>
</ul>
### Installation
```bash
dotnet add package Logto.AspNetCore.Authentication
```
<Installation />
</Step>
<Step title="Add Logto authentication">
Open `Startup.cs` (or `Program.cs`) and add the following code to register Logto authentication middleware:
<AddAuthentication {...props} />
<Code className="language-csharp">
{`using Logto.AspNetCore.Authentication;
</Step>
var builder = WebApplication.CreateBuilder(args);
<Step title="Understand sign-in and sign-out flows">
builder.Services.AddLogtoAuthentication(options =>
{
options.Endpoint = "${props.endpoint}";
options.AppId = "${props.app.id}";
options.AppSecret = "${props.app.secret}";
});
<SignInAndSignOutFlows />
app.UseAuthentication();`}
</Code>
</Step>
The `AddLogtoAuthentication` method will do the following things:
<Step title="Configure redirect URIs">
- Set the default authentication scheme to `LogtoDefaults.CookieScheme`.
- Set the default challenge scheme to `LogtoDefaults.AuthenticationScheme`.
- Set the default sign-out scheme to `LogtoDefaults.AuthenticationScheme`.
- Add cookie and OpenID Connect authentication handlers to the authentication scheme.
<ConfigureRedirectUris />
</Step>
@ -54,7 +39,7 @@ Since Blazor Server uses SignalR to communicate between the server and the clien
To make it right, we need to explicitly add two endpoints for sign-in and sign-out redirects:
```csharp
```csharp title="Program.cs"
app.MapGet("/SignIn", async context =>
{
if (!(context.User?.Identity?.IsAuthenticated ?? false))
@ -80,35 +65,11 @@ Now we can redirect to these endpoints to trigger sign-in and sign-out.
</Step>
<Step title="Set up redirect URIs">
<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" />
Remember to keep the path `/Callback` in the URI as it's the default value for the Logto authentication middleware.
---
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" />
Remember to keep the path `/SignedOutCallback` in the URI as it's the default value for the Logto authentication middleware.
</Step>
<Step title="Sign-in and sign-out">
In the Razor component, add the following code:
```cshtml
```cshtml title="Components/Pages/Index.razor"
@using Microsoft.AspNetCore.Components.Authorization
@using System.Security.Claims
@inject AuthenticationStateProvider AuthenticationStateProvider
@ -158,41 +119,13 @@ The page will show the "Sign in" button if the user is not authenticated, and sh
</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 know if the user is authenticated, you can check the `User.Identity?.IsAuthenticated` property.
To get the user profile claims, you can use the `User.Claims` property:
```csharp
var claims = User.Claims;
// Get the user ID
var userId = claims.FirstOrDefault(c => c.Type == LogtoParameters.Claims.Subject)?.Value;
```
See the [full tutorial](https://docs.logto.io/quick-starts/dotnet-core/blazor-server/) for more details.
</Step>
<Step title="The `<AuthorizeView />` component">
<Step title="Alternative: Use the `AuthorizeView` component">
Alternatively, you can use the `AuthorizeView` component to conditionally render content based on the user's authentication state. This component is useful when you want to show different content to authenticated and unauthenticated users.
In your Razor component, add the following code:
```cshtml
```cshtml title="Components/Pages/Index.razor"
@using Microsoft.AspNetCore.Components.Authorization
@* ... *@
@ -212,7 +145,7 @@ In your Razor component, add the following code:
The `AuthorizeView` component requires a cascading parameter of type `Task<AuthenticationState>`. A direct way to get this parameter is to add the `<CascadingAuthenticationState>` component. However, due to the nature of Blazor Server, we cannot simply add the component to the layout or the root component (it may not work as expected). Instead, we can add the following code to the builder (`Program.cs` or `Startup.cs`) to provide the cascading parameter:
```csharp
```csharp title="Program.cs"
builder.Services.AddCascadingAuthenticationState();
```
@ -220,4 +153,16 @@ Then you can use the `AuthorizeView` component in every component that needs it.
</Step>
<Step title="Checkpoint: Test your application">
<Checkpoint />
</Step>
<Step title="Display user information">
<DisplayUserInformation />
</Step>
</Steps>

View file

@ -2,15 +2,14 @@ import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
import Checkpoint from '../../fragments/_checkpoint.md';
import RedirectUrisWeb, { defaultRedirectUri, defaultPostSignOutUri } from '../../fragments/_redirect-uris-web.mdx';
<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>
This guide will show you how to use [Blorc.OpenIdConnect](https://github.com/WildGums/Blorc.OpenIdConnect) to add Logto authentication to a Blazor WebAssembly application.
### Installation
@ -26,7 +25,7 @@ dotnet add package Blorc.OpenIdConnect
Include `Blorc.Core/injector.js` the `index.html` file:
```html
```html title="index.html"
<head>
<!-- ... -->
<script src="_content/Blorc.Core/injector.js"></script>
@ -38,7 +37,7 @@ Include `Blorc.Core/injector.js` the `index.html` file:
Add the following code to the `Program.cs` file:
```csharp
```csharp title="Program.cs"
using Blorc.OpenIdConnect;
using Blorc.Services;
@ -66,37 +65,23 @@ Note: There's no need to use the `Microsoft.AspNetCore.Components.WebAssembly.Au
</Step>
<Step title="Configure Logto">
<Step title="Configure redirect URIs">
### Configure redirect URI
<RedirectUrisWeb />
<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>
</Step>
<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
<Step title="Configure application">
Add the following code to the `appsettings.json` file:
<Code className="language-json5">
<Code className="language-json5" title="appsettings.json">
{`// ...
IdentityServer: {
Authority: '${props.endpoint}oidc',
ClientId: '${props.app.id}',
RedirectUri: '${props.redirectUris[0] ?? props.sampleUrls.callback}',
PostLogoutRedirectUri: '${props.postLogoutRedirectUris[0] ?? props.sampleUrls.origin}',
RedirectUri: '${props.redirectUris[0] ?? defaultRedirectUri}',
PostLogoutRedirectUri: '${props.postLogoutRedirectUris[0] ?? defaultPostSignOutUri}',
ResponseType: 'code',
Scope: 'openid profile', // Add more scopes if needed
},
@ -112,7 +97,7 @@ Add the following code to the `appsettings.json` file:
In the Razor pages that require authentication, add the `AuthorizeView` component. Let's assume it's the `Home.razor` page:
```cshtml
```cshtml title="Pages/Home.razor"
@using Microsoft.AspNetCore.Components.Authorization
@page "/"
@ -136,7 +121,7 @@ In the Razor pages that require authentication, add the `AuthorizeView` componen
In the `Home.razor.cs` file (create it if it doesn't exist), add the following code:
```csharp
```csharp title="Pages/Home.razor.cs"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
@ -173,11 +158,19 @@ public partial class Home : ComponentBase
Once the user is authenticated, the `User` property will be populated with the user information.
### Display user information
</Step>
<Step title="Checkpoint: Test your application">
<Checkpoint />
</Step>
<Step title="Display user information">
Here are some examples of how to display user information in the `Home.razor` page:
```cshtml
```cshtml title="Pages/Home.razor"
<AuthorizeView>
<Authorized>
@* Signed in view *@
@ -192,23 +185,4 @@ For more properties and claims, check the `User` and `Profile` classes in the `B
</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/quick-starts/dotnet-core/blazor-wasm/) for more details.
</Step>
</Steps>

View file

@ -2,141 +2,68 @@ import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
import Checkpoint from '../../fragments/_checkpoint.md';
import SignInAndSignOutFlows from './fragments/_sign-in-and-sign-out-flows.mdx';
import ConfigureRedirectUris from './fragments/_configure-redirect-uris.mdx';
import Installation from './fragments/_installation.md';
import AddAuthentication from './fragments/_add-authentication.mdx';
import DisplayUserInformation from './fragments/_display-user-information.md';
<Steps>
<Step title="Get started">
<Step title="Add Logto SDK as a dependency">
This tutorial will show you how to use Logto ASP.NET Core authentication middleware to protect your web application.
<ul>
<li>It assumes your website is hosted on <code>{props.sampleUrls.origin}</code>.</li>
</ul>
### Installation
```bash
dotnet add package Logto.AspNetCore.Authentication
```
<Installation />
</Step>
<Step title="Add Logto authentication">
Open `Startup.cs` (or `Program.cs`) and add the following code to register Logto authentication middleware:
<Code className="language-csharp">
{`using Logto.AspNetCore.Authentication;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLogtoAuthentication(options =>
{
options.Endpoint = "${props.endpoint}";
options.AppId = "${props.app.id}";
options.AppSecret = "${props.app.secret}";
});
app.UseAuthentication();`}
</Code>
The `AddLogtoAuthentication` method will do the following things:
- Set the default authentication scheme to `LogtoDefaults.CookieScheme`.
- Set the default challenge scheme to `LogtoDefaults.AuthenticationScheme`.
- Set the default sign-out scheme to `LogtoDefaults.AuthenticationScheme`.
- Add cookie and OpenID Connect authentication handlers to the authentication scheme.
<AddAuthentication {...props} />
</Step>
<Step title="Sign-in">
<Step title="Understand sign-in and sign-out flows">
<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>
<SignInAndSignOutFlows />
<UriInputField name="redirectUris" />
</Step>
Remember to keep the path `/Callback` in the URI as it's the default value for the Logto authentication middleware.
<Step title="Configure redirect URIs">
To sign-in with Logto, you can use the `Challenge` method of `ControllerBase`:
<ConfigureRedirectUris />
```csharp
Challenge(new AuthenticationProperties
{
// The URI below is different from the redirect URI you entered above.
// It's the URI where users will be redirected after successfully signed in.
// You can change it to any path you want.
RedirectUri = "/"
});
```
</Step>
For example, you can add the following code to the controller:
<Step title="Implement sign-in and sign-out buttons">
```csharp
First, add actions methods to your `Controller`, for example:
```csharp title="Controllers/HomeController.cs"
public class HomeController : Controller
{
public IActionResult SignIn()
{
// This will redirect the user to the Logto sign-in page.
return Challenge(new AuthenticationProperties { RedirectUri = "/" });
}
}
```
And then add the following code to your View:
```html
<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
<a asp-controller="Home" asp-action="SignIn">Sign in</a>
```
</Step>
<Step title="Sign-out">
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" />
Remember to keep the path `/SignedOutCallback` in the URI as it's the default value for the Logto authentication middleware.
To sign-out with Logto, you can use the `SignOut` method of `ControllerBase`:
```csharp
SignOut(new AuthenticationProperties
{
// The URI below is different from the post sign-out redirect URI you entered above.
// It's the URI where users will be redirected after successfully signed out.
// You can change it to any path you want.
RedirectUri = "/"
});
```
The `SignOut` method will clear the authentication cookie and redirect the user to the Logto sign-out page.
For example, you can add the following code to your controller:
```csharp
public class HomeController : Controller
{
// ...
// Use the `new` keyword to avoid conflict with the `ControllerBase.SignOut` method
new public IActionResult SignOut()
{
// This will clear the authentication cookie and redirect the user to the Logto sign-out page
// to clear the Logto session as well.
return SignOut(new AuthenticationProperties { RedirectUri = "/" });
}
}
```
Then, update the form on your View:
Then, add the links to your View:
```html
```cshtml title="Views/Home/Index.cshtml"
<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
@if (User.Identity?.IsAuthenticated == true)
{
@if (User.Identity?.IsAuthenticated == true) {
<a asp-controller="Home" asp-action="SignOut">Sign out</a>
} else {
<a asp-controller="Home" asp-action="SignIn">Sign in</a>
@ -149,29 +76,13 @@ It will show the "Sign in" link if the user is not authenticated, and show the "
<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" link.
2. Click the "Sign in" link, 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" link.
4. Click the "Sign out" link, and you should be redirected to the Logto sign-out page, and then redirected back to the web application.
<Checkpoint />
</Step>
<Step title="The user object">
<Step title="Display user information">
To know if the user is authenticated, you can check the `User.Identity?.IsAuthenticated` property.
To get the user profile claims, you can use the `User.Claims` property:
```csharp
var claims = User.Claims;
// Get the user ID
var userId = claims.FirstOrDefault(c => c.Type == LogtoParameters.Claims.Subject)?.Value;
```
See the [full tutorial](https://docs.logto.io/quick-starts/dotnet-core/mvc/) for more details.
<DisplayUserInformation />
</Step>

View file

@ -0,0 +1,23 @@
Open `Startup.cs` (or `Program.cs`) and add the following code to register Logto authentication middleware:
<Code title="Program.cs" className="language-csharp">
{`using Logto.AspNetCore.Authentication;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLogtoAuthentication(options =>
{
options.Endpoint = "${props.endpoint}";
options.AppId = "${props.app.id}";
options.AppSecret = "${props.app.secret}";
});
app.UseAuthentication();`}
</Code>
The `AddLogtoAuthentication` method will do the following things:
- Set the default authentication scheme to `LogtoDefaults.CookieScheme`.
- Set the default challenge scheme to `LogtoDefaults.AuthenticationScheme`.
- Set the default sign-out scheme to `LogtoDefaults.AuthenticationScheme`.
- Add cookie and OpenID Connect authentication handlers to the authentication scheme.

View file

@ -0,0 +1,28 @@
import UriInputField from '@/mdx-components/UriInputField';
export const defaultBaseUrl = 'http://localhost:5000/';
First, let's configure the **Logto redirect URI**. For example, if your website is hosted on <code>{defaultBaseUrl}</code>, add <code>{defaultBaseUrl + 'Callback'}</code> as the redirect URI below:
<UriInputField name="redirectUris" />
Now let's configure the **Logto post sign-out redirect URI**. For example, set the URI to <code>{defaultBaseUrl + 'SignedOutCallback'}</code>:
<UriInputField name="postLogoutRedirectUris" />
#### Change the default paths
The **Logto redirect URI** has a default path of `/Callback`, and the **Logto post sign-out redirect URI** has a default path of `/SignedOutCallback`.
You can leave them as are if there's no special requirement. If you want to change it, you can set the `CallbackPath` and `SignedOutCallbackPath` property for `LogtoOptions`:
```csharp title="Program.cs"
builder.Services.AddLogtoAuthentication(options =>
{
// Other configurations...
options.CallbackPath = "/Foo";
options.SignedOutCallbackPath = "/Bar";
});
```
Remember to update the values in the redirect URI fields accordingly.

View file

@ -0,0 +1,12 @@
To know if the user is authenticated, you can check the `User.Identity?.IsAuthenticated` property.
To get the user profile claims, you can use the `User.Claims` property:
```csharp title="Controllers/HomeController.cs"
var claims = User.Claims;
// Get the user ID
var userId = claims.FirstOrDefault(c => c.Type == LogtoParameters.Claims.Subject)?.Value;
```
See [`LogtoParameters.Claims`](https://github.com/logto-io/csharp/blob/master/src/Logto.AspNetCore.Authentication/LogtoParameters.cs) for the list of claim names and their meanings.

View file

@ -0,0 +1,5 @@
Install the Logto SDK to your project:
```bash showLineNumbers={false}
dotnet add package Logto.AspNetCore.Authentication
```

View file

@ -0,0 +1,37 @@
import RegardingRedirectBasedSignIn from '../../../fragments/_regarding-redirect-based-sign-in.md';
Before we proceed, there are two confusing terms in the .NET Core authentication middleware that we need to clarify:
1. **CallbackPath**: The URI that Logto will redirect the user back to after the user has signed in (the "redirect URI" in Logto)
2. **RedirectUri**: The URI that will be redirected to after necessary actions have been taken in the Logto authentication middleware.
The sign-in process can be illustrated as follows:
```mermaid
graph LR
subgraph Your app
A
C
D
end
subgraph Logto
B
end
A(Sign-in path) -->|Redirect to| B(Logto)
B -->|Redirect to| C(CallbackPath)
C -->|Redirect to| D(RedirectUri)
```
<br />
Similarly, .NET Core also has **SignedOutCallbackPath** and **RedirectUri** for the sign-out flow.
For the sack of clarity, we'll refer them as follows:
| Term we use | .NET Core term |
| -------------------------------- | --------------------- |
| Logto redirect URI | CallbackPath |
| Logto post sign-out redirect URI | SignedOutCallbackPath |
| Application redirect URI | RedirectUri |
<RegardingRedirectBasedSignIn />

View file

@ -2,80 +2,46 @@ import UriInputField from '@/mdx-components/UriInputField';
import Steps from '@/mdx-components/Steps';
import Step from '@/mdx-components/Step';
import SignInAndSignOutFlows from '../web-dotnet-core-mvc/fragments/_sign-in-and-sign-out-flows.mdx';
import ConfigureRedirectUris from '../web-dotnet-core-mvc/fragments/_configure-redirect-uris.mdx';
import Installation from '../web-dotnet-core-mvc/fragments/_installation.md';
import AddAuthentication from '../web-dotnet-core-mvc/fragments/_add-authentication.mdx';
import DisplayUserInformation from '../web-dotnet-core-mvc/fragments/_display-user-information.md';
import Checkpoint from '../../fragments/_checkpoint.md';
<Steps>
<Step title="Get started">
<Step title="Add Logto SDK as a dependency">
This tutorial will show you how to use Logto ASP.NET Core authentication middleware to protect your web application.
<ul>
<li>It assumes your website is hosted on <code>{props.sampleUrls.origin}</code>.</li>
</ul>
### Installation
```bash
dotnet add package Logto.AspNetCore.Authentication
```
<Installation />
</Step>
<Step title="Add Logto authentication">
Open `Startup.cs` (or `Program.cs`) and add the following code to register Logto authentication middleware:
<Code className="language-csharp">
{`using Logto.AspNetCore.Authentication;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLogtoAuthentication(options =>
{
options.Endpoint = "${props.endpoint}";
options.AppId = "${props.app.id}";
options.AppSecret = "${props.app.secret}";
});
app.UseAuthentication();`}
</Code>
The `AddLogtoAuthentication` method will do the following things:
- Set the default authentication scheme to `LogtoDefaults.CookieScheme`.
- Set the default challenge scheme to `LogtoDefaults.AuthenticationScheme`.
- Set the default sign-out scheme to `LogtoDefaults.AuthenticationScheme`.
- Add cookie and OpenID Connect authentication handlers to the authentication scheme.
<AddAuthentication {...props} />
</Step>
<Step title="Sign-in">
<Step title="Understand sign-in and sign-out flows">
<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>
<SignInAndSignOutFlows />
<UriInputField name="redirectUris" />
</Step>
Remember to keep the path `/Callback` in the URI as it's the default value for the Logto authentication middleware.
<Step title="Configure redirect URIs">
To sign-in with Logto, you can use the `ChallengeAsync` method:
<ConfigureRedirectUris />
```csharp
await HttpContext.ChallengeAsync(new AuthenticationProperties
{
// The URI below is different from the redirect URI you entered above.
// It's the URI where users will be redirected after successfully signed in.
// You can change it to any path you want.
RedirectUri = "/"
});
```
</Step>
For example, if you are using Razor Pages, you can add the following code to the `Index` page model:
<Step title="Implement sign-in and sign-out">
```csharp
First, add the handler methods to your `PageModel`, for example:
```csharp title="Pages/Index.cshtml.cs"
public class IndexModel : PageModel
{
// ...
public async Task OnPostSignInAsync()
{
await HttpContext.ChallengeAsync(new AuthenticationProperties
@ -83,52 +49,7 @@ public class IndexModel : PageModel
RedirectUri = "/"
});
}
}
```
And then add the following code to the `Index` page:
```html
<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
<form method="post">
<button type="submit" asp-page-handler="SignIn">Sign in</button>
</form>
```
</Step>
<Step title="Sign-out">
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" />
Remember to keep the path `/SignedOutCallback` in the URI as it's the default value for the Logto authentication middleware.
To sign-out with Logto, you can use the `SignOutAsync` method:
```csharp
await HttpContext.SignOutAsync(new AuthenticationProperties
{
// The URI below is different from the post sign-out redirect URI you entered above.
// It's the URI where users will be redirected after successfully signed out.
// You can change it to any path you want.
RedirectUri = "/"
});
```
The `SignOutAsync` method will clear the authentication cookie and redirect the user to the Logto sign-out page.
For example, if you are using Razor Pages, you can add the following code to the `Index` page model:
```csharp
public class IndexModel : PageModel
{
// ...
public async Task OnPostSignOutAsync()
{
await HttpContext.SignOutAsync(new AuthenticationProperties
@ -139,13 +60,12 @@ public class IndexModel : PageModel
}
```
Then, update the form on your Razor page:
Then, add the buttons to your Razor page:
```html
```cshtml title="Pages/Index.cshtml"
<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
<form method="post">
@if (User.Identity?.IsAuthenticated == true)
{
@if (User.Identity?.IsAuthenticated == true) {
<button type="submit" asp-page-handler="SignOut">Sign out</button>
} else {
<button type="submit" asp-page-handler="SignIn">Sign in</button>
@ -159,29 +79,13 @@ It will show the "Sign in" button if the user is not authenticated, and show the
<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.
<Checkpoint />
</Step>
<Step title="The user object">
<Step title="Display user information">
To know if the user is authenticated, you can check the `User.Identity?.IsAuthenticated` property.
To get the user profile claims, you can use the `User.Claims` property:
```csharp
var claims = User.Claims;
// Get the user ID
var userId = claims.FirstOrDefault(c => c.Type == LogtoParameters.Claims.Subject)?.Value;
```
See the [full tutorial](https://docs.logto.io/quick-starts/dotnet-core/razor/) for more details.
<DisplayUserInformation />
</Step>

View file

@ -9,7 +9,7 @@ import RedirectUrisWeb from '../../fragments/_redirect-uris-web.mdx';
<Step title="Get started">
This tutorial will show you how to integrate Logto into your Java Spring Boot web application.
This tutorial will show you how to integrate Logto into your Java Spring Boot application.
No official SDK is required to integrate Logto with your Java Spring Boot application. We will use the [Spring Security](https://spring.io/projects/spring-security) and [Spring Security OAuth2](https://spring.io/guides/tutorials/spring-boot-oauth2) libraries to handle the OIDC authentication flow with Logto.

View file

@ -3,7 +3,7 @@ import { ApplicationType } from '@logto/schemas';
import { type GuideMetadata } from '../types';
const metadata: Readonly<GuideMetadata> = Object.freeze({
name: 'Java Spring Boot web',
name: 'Java Spring Boot',
description:
'Spring Boot is a web framework for Java that enables developers to build secure, fast, and scalable server applications with the Java programming language.',
target: ApplicationType.Traditional,

View file

@ -3,7 +3,7 @@ import { ApplicationType } from '@logto/schemas';
import { type GuideMetadata } from '../types';
const metadata: Readonly<GuideMetadata> = Object.freeze({
name: 'Next.js',
name: 'Next.js (Page Router)',
description:
'Next.js is a React framework for production - it makes building fullstack React apps a breeze and ships with built-in SSR.',
target: ApplicationType.Traditional,

View file

@ -22,10 +22,6 @@ export type GuideContextType = {
endpoint?: string;
redirectUris?: string[];
postLogoutRedirectUris?: string[];
sampleUrls?: {
origin: string;
callback: string;
};
audience?: string;
};
@ -48,7 +44,6 @@ export const GuideContext = createContext<GuideContextType>({
redirectUris: [],
postLogoutRedirectUris: [],
isCompact: false,
sampleUrls: { origin: '', callback: '' },
audience: '',
});

View file

@ -102,6 +102,8 @@ function ApplicationDetailsContent({ data, oidcConfig, onApplicationUpdated }: P
};
const onCloseDrawer = () => {
// The guide drawer may have updated the application data
onApplicationUpdated();
setIsReadmeOpen(false);
};

View file

@ -32,10 +32,6 @@ function AppGuide({ className, guideId, app, isCompact, onClose }: Props) {
redirectUris: app.oidcClientMetadata.redirectUris,
postLogoutRedirectUris: app.oidcClientMetadata.postLogoutRedirectUris,
isCompact: Boolean(isCompact),
sampleUrls: {
origin: 'http://localhost:3001/',
callback: 'http://localhost:3001/callback',
},
}
) satisfies GuideContextType | undefined,
[guide, app, tenantEndpoint?.href, applyCustomDomain, isCompact]