Nothing Special   »   [go: up one dir, main page]

Skip to main content

.NET Core: Integrate Logto with MVC app

tip
  • The following demonstration is built on .NET Core 8.0. The SDK is compatible with .NET 6.0 or higher.
  • The .NET Core sample projects are available in the GitHub repository.

Prerequisites

  • A Logto Cloud account or a self-hosted Logto (Check out the ⚡ Get started guide to create one if you don't have).
  • A Logto traditional web application created.

Installation

Add the NuGet package to your project:

dotnet add package Logto.AspNetCore.Authentication

Integration

Add Logto authentication

Open Startup.cs (or Program.cs) and add the following code to register Logto authentication services:

Program.cs
using Logto.AspNetCore.Authentication;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddLogtoAuthentication(options =>
{
options.Endpoint = builder.Configuration["Logto:Endpoint"]!;
options.AppId = builder.Configuration["Logto:AppId"]!;
options.AppSecret = builder.Configuration["Logto:AppSecret"];
});

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.

Sign-in and sign-out flows

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:


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 URICallbackPath
Logto post sign-out redirect URISignedOutCallbackPath
Application redirect URIRedirectUri
Regarding redirect-based sign-in
  1. This authentication process follows the OpenID Connect (OIDC) 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.

Configure redirect URIs

note

In the following code snippets, we assume your app is running on http://localhost:3000/.

First, let's configure the Logto redirect URI. Add the following URI to the "Redirect URIs" list in the Logto application details page:

http://http://localhost:3000//Callback

To configure the Logto post sign-out redirect URI, add the following URI to the "Post sign-out redirect URIs" list in the Logto application details page:

http://http://localhost:3000//SignedOutCallback

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:

Program.cs
builder.Services.AddLogtoAuthentication(options =>
{
// Other configurations...
options.CallbackPath = "/Foo";
options.SignedOutCallbackPath = "/Bar";
});

Remember to update the value in the Logto application details page accordingly.

Implement sign-in and sign-out buttons

First, add actions methods to your Controller, for example:

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 = "/" });
}

// 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, add the links to your View:

Views/Home/Index.cshtml
<p>Is authenticated: @User.Identity?.IsAuthenticated</p>
@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>
}

It will show the "Sign in" link if the user is not authenticated, and show the "Sign out" link if the user is authenticated.

Checkpoint: Test your application

Now, you can test your application:

  1. Run your application, you will see the sign-in button.
  2. Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
  3. After you signed in, you will be redirected back to your application and see the sign-out button.
  4. Click the sign-out button to clear local storage and sign out.

Get user information

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:

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 for the list of claim names and their meanings.

Request additional claims

You may find some user information are missing in the returned object from User.Claims. This is because OAuth 2.0 and OpenID Connect (OIDC) are designed to follow the principle of least privilege (PoLP), and Logto is built on top of these standards.

By default, limited claims are returned. If you need more information, you can request additional scopes to access more claims.

info

A "claim" is an assertion made about a subject; a "scope" is a group of claims. In the current case, a claim is a piece of information about the user.

Here's a non-normative example the scope - claim relationship:

tip

The "sub" claim means "subject", which is the unique identifier of the user (i.e. user ID).

Logto SDK will always request three scopes: openid, profile, and offline_access.

To request additional scopes, you can configure the Scopes property in the options object:

Program.cs
builder.Services.AddLogtoAuthentication(options =>
{
// ...
options.Scopes = new string[] {
LogtoParameters.Scopes.Email,
LogtoParameters.Scopes.Phone
}
});

Then you can access the additional claims via User.Claims:

Controllers/HomeController.cs
var claims = User.Claims;

// Get the user email
var email = claims.FirstOrDefault(c => c.Type == LogtoParameters.Claims.Email)?.Value;

Claims that need network request

To prevent bloating the user object, some claims require network requests to fetch. For example, the custom_data claim is not included in the user object even if it's requested in the scopes. To fetch these claims, you can set GetClaimsFromUserInfoEndpoint to true in the options object:

Program.cs
builder.Services.AddLogtoAuthentication(options =>
{
// ...
options.GetClaimsFromUserInfoEndpoint = true;
});

Scopes and claims

Logto uses OIDC scopes and claims conventions to define the scopes and claims for retrieving user information from the ID token and OIDC userinfo endpoint. Both of the "scope" and the "claim" are terms from the OAuth 2.0 and OpenID Connect (OIDC) specifications.

Here's the list of supported scopes and the corresponding claims:

openid

Claim nameTypeDescriptionNeeds userinfo?
substringThe unique identifier of the userNo

profile

Claim nameTypeDescriptionNeeds userinfo?
namestringThe full name of the userNo
usernamestringThe username of the userNo
picturestringURL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User.No
created_atnumberTime the End-User was created. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No
updated_atnumberTime the End-User's information was last updated. The time is represented as the number of milliseconds since the Unix epoch (1970-01-01T00:00:00Z).No

Other standard claims include family_name, given_name, middle_name, nickname, preferred_username, profile, website, gender, birthdate, zoneinfo, and locale will be also included in the profile scope without the need for requesting the userinfo endpoint. A difference compared to the claims above is that these claims will only be returned when their values are not empty, while the claims above will return null if the values are empty.

note

Unlike the standard claims, the created_at and updated_at claims are using milliseconds instead of seconds.

email

Claim nameTypeDescriptionNeeds userinfo?
emailstringThe email address of the userNo
email_verifiedbooleanWhether the email address has been verifiedNo

phone

Claim nameTypeDescriptionNeeds userinfo?
phone_numberstringThe phone number of the userNo
phone_number_verifiedbooleanWhether the phone number has been verifiedNo

address

Please refer to the OpenID Connect Core 1.0 for the details of the address claim.

custom_data

Claim nameTypeDescriptionNeeds userinfo?
custom_dataobjectThe custom data of the userYes

identities

Claim nameTypeDescriptionNeeds userinfo?
identitiesobjectThe linked identities of the userYes
sso_identitiesarrayThe linked SSO identities of the userYes

urn:logto:scope:organizations

Claim nameTypeDescriptionNeeds userinfo?
organizationsstring[]The organization IDs the user belongs toNo
organization_dataobject[]The organization data the user belongs toYes

urn:logto:scope:organization_roles

Claim nameTypeDescriptionNeeds userinfo?
organization_rolesstring[]The organization roles the user belongs to with the format of <organization_id>:<role_name>No

Considering performance and the data size, if "Needs userinfo?" is "Yes", it means the claim will not show up in the ID token, but will be returned in the userinfo endpoint response.

API resources

We recommend to read 🔐 Role-Based Access Control (RBAC) first to understand the basic concepts of Logto RBAC and how to set up API resources properly.

Configure API resource in your app

Once you have set up the API resources, you can add them when configuring Logto in your app:

Program.cs
builder.Services.AddLogtoAuthentication(options =>
{
// ...
options.Resource = "https://<your-api-resource-indicator>";
});

Each API resource has its own permissions (scopes).

For example, the https://shopping.your-app.com/api resource has the shopping:read and shopping:write permissions, and the https://store.your-app.com/api resource has the store:read and store:write permissions.

To request these permissions, you can add them when configuring Logto in your app:

Program.cs
builder.Services.AddLogtoAuthentication(options =>
{
// ...
options.Resource = "https://shopping.your-app.com/api";
options.Scopes = new string[] {
"openid",
"profile",
"offline_access",
"read",
"write"
};
});

You may notice that scopes are defined separately from API resources. This is because Resource Indicators for OAuth 2.0 specifies the final scopes for the request will be the cartesian product of all the scopes at all the target services.

note

It is fine to request scopes that are not defined in the API resources. For example, you can request the email scope even if the API resources don't have the email scope available. Unavailable scopes will be safely ignored.

After the successful sign-in, Logto will issue proper scopes to API resources according to the user's roles.

Fetch tokens

Sometimes you may need to fetch the access token or ID token for API calls. You can use the GetTokenAsync method to fetch the tokens:

var accessToken = await HttpContext.GetTokenAsync(LogtoParameters.Tokens.AccessToken);
var idToken = await HttpContext.GetTokenAsync(LogtoParameters.Tokens.IdToken);

No need to worry about the token expiration, the authentication middleware will automatically refresh the tokens when necessary.

caution

Although the authentication middleware will automatically refresh the tokens, the claims in the user object will not be updated due to the limitation of the underlying OpenID Connect authentication handler. This can be resolved once we write our own authentication handler.

Note the access token above is an opaque token for the userinfo endpoint in OpenID Connect, which is not a JWT token. If you have specified the API resource, you need to use LogtoParameters.Tokens.AccessTokenForResource to fetch the access token for the API resource:

var accessToken = await HttpContext.GetTokenAsync(LogtoParameters.Tokens.AccessTokenForResource);

This token will be a JWT token with the API resource as the audience.

Further readings