Skip to content
Merged
Show file tree
Hide file tree
Changes from 57 commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
d224fad
Initial structure
damienbod Oct 22, 2024
09fe109
Link menu
damienbod Oct 22, 2024
6884d25
Add sample
damienbod Oct 23, 2024
557e270
Update new authentication for OIDC
damienbod Oct 23, 2024
a5ea417
samples
damienbod Oct 23, 2024
f6f462b
Add links from the used standards
damienbod Oct 23, 2024
b0692db
Add a reference link
damienbod Oct 23, 2024
e9d4040
Update sections
damienbod Oct 23, 2024
0f34cb5
Add a link
damienbod Oct 23, 2024
22b5ec4
Add some definitions
damienbod Oct 23, 2024
149fd91
Add image
damienbod Oct 23, 2024
f850f78
Update image
damienbod Oct 23, 2024
9535563
Add an Overview
damienbod Oct 23, 2024
31dec59
Update docs
damienbod Oct 23, 2024
88fd2f2
Update doc
damienbod Oct 23, 2024
6f699ef
Add customizations
damienbod Oct 23, 2024
b117a14
Update sections
damienbod Oct 23, 2024
a4559ba
Add more data
damienbod Oct 23, 2024
0db2826
Add third party information
damienbod Oct 23, 2024
4e80b45
Update texts
damienbod Oct 23, 2024
185cb8a
add background to image
damienbod Oct 23, 2024
b140eb9
clean up
damienbod Oct 23, 2024
8c3b3c2
remove file
damienbod Oct 23, 2024
8bb3e27
Update text
damienbod Oct 23, 2024
66c08f9
Update text
damienbod Oct 23, 2024
2caea0d
Update text
damienbod Oct 23, 2024
798b75c
text
damienbod Oct 23, 2024
98ea9d8
fix line 80
damienbod Oct 24, 2024
7e5d4c4
fix link
damienbod Oct 24, 2024
5f34f37
link change due to build line 15
damienbod Oct 24, 2024
002e14d
build test
damienbod Oct 24, 2024
81d26a4
Remove toc link due to build in dev branch
damienbod Oct 24, 2024
8a80c23
reset link, no change to build
damienbod Oct 24, 2024
b29c522
fix links
damienbod Oct 24, 2024
a0c986c
Test add toc menu
damienbod Oct 24, 2024
e29e969
Connect not connect
damienbod Oct 24, 2024
3ae9d22
Improve image
damienbod Oct 24, 2024
d88cffe
fix small typos
damienbod Oct 24, 2024
f761a91
typo
damienbod Oct 24, 2024
c4a3261
Update configuration
damienbod Nov 9, 2024
19e667c
Update programs
damienbod Nov 9, 2024
8199ed2
Use FallbackPolicy instead of MVC options
damienbod Nov 9, 2024
5a7e807
UseAuthorization() comment
damienbod Nov 9, 2024
b342f94
Clean up sample using feedback
damienbod Nov 9, 2024
4a9e039
code clean up
damienbod Nov 9, 2024
f0f5789
Update text based on PR feedback
damienbod Nov 9, 2024
c6355bc
2 spaces
damienbod Nov 9, 2024
bc7afe1
Update text
damienbod Nov 9, 2024
1a974a5
Update text
damienbod Nov 9, 2024
708bd1b
Improve text
damienbod Nov 9, 2024
1a2143a
text
damienbod Nov 9, 2024
a802049
Update sample
damienbod Nov 9, 2024
72dcd60
Update sample
damienbod Nov 9, 2024
d4714b0
Fix code example
damienbod Nov 9, 2024
f64b6a6
spaces
damienbod Nov 9, 2024
2114f6a
spaces
damienbod Nov 9, 2024
5e558c4
spaces
damienbod Nov 9, 2024
5846b59
PR feedback
damienbod Nov 12, 2024
7d29cd4
Improve text
damienbod Nov 12, 2024
d250ac7
Update schemes doc
damienbod Nov 12, 2024
8bf7c68
logout
damienbod Nov 12, 2024
e3af7a1
rename claim mappings
damienbod Nov 12, 2024
9e75b67
Update code
damienbod Nov 12, 2024
52d26d5
Update link
damienbod Nov 12, 2024
4197943
Update link
damienbod Nov 12, 2024
c3017ff
fix link
damienbod Nov 12, 2024
8ee2ea4
logging
damienbod Nov 12, 2024
a888f3c
Update links
damienbod Nov 12, 2024
42aa032
fix spacing
damienbod Nov 12, 2024
22c93e3
grammer
damienbod Nov 12, 2024
ef96027
grammer
damienbod Nov 12, 2024
f05ca90
Add Login page
damienbod Nov 12, 2024
ebce90d
Add a challenge
damienbod Nov 12, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,317 @@
---
title: Configure OpenID Connect Web (UI) authentication in ASP.NET Core
author: damienbod
description: Learn how to set up OpenID Connect authentication in an ASP.NET Core app.
monikerRange: '>= aspnetcore-8.0'
ms.author: riande
ms.custom: mvc
ms.date: 04/02/2024
uid: security/authentication/configure-oidc-web-authentication
---
# Configure OpenID Connect Web (UI) authentication in ASP.NET Core

By [Damien Bowden](https://github.com/damienbod)

[View or download sample code](https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/security/authentication/configure-oidc-web-authentication/sample/oidc-net8)

This article covers the following areas:

* What is an OpenID Connect confidential interactive client
* Create an OpenID Connect client in ASP.NET Core
* Examples of OpenID Connect client with code snippets
* Using third party OpenID Connect provider clients
* Backend for frontend (BFF) security architecture
* Advanced features, standards, extending the an OpenID Connect client

## What is an OpenID Connect confidential interactive client

[OpenID Connect](https://openid.net/developers/how-connect-works/) can be used to implement authentication in ASP.NET Core applications. The recommended way is to use an OpenID Connect confidential client using the code flow. Using the [Proof Key for Code Exchange by OAuth Public Clients (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) is recommended for this implementation. Both the application client and the user of the application are authenticated in the confidential flow. The application client uses a client secret or a client assertion to authenticate.

Public OpenID Connect/OAuth clients are no longer recommended for web applications.

The default flow works as shown in the following diagram:

![OIDC code flow confidential client using PKCE](~/security/authentication/configure-oidc-web-authentication/_static/oidc-confidential-pkce-flow-drawio.png)

OpenID Connect comes in many variations and all server implementations have slightly different parameters and requirements. Some servers don’t support the user info endpoint, some still don’t support PKCE and others require special parameters in the token request. Client assertions can be used instead of client secrets. New standards also exist which add extra security on top of the OpenID Connect Core, for example FAPI, CIBA or DPoP for downstream APIs.

> [!NOTE]
> From .NET 9, [OAuth 2.0 Pushed Authorization Requests (PAR) RFC 9126](https://datatracker.ietf.org/doc/html/rfc9126) is used per default, if the OpenID Connect server supports this. This is a three step flow and not a two step flow as shown above. (User Info request is an optional step.)

## Create an Open ID Connect code flow client using Razor Pages

The following section shows how to implement an OpenID Connect client in an empty ASP.NET Core Razor page project. The same logic can be applied to any ASP.NET Core web project with only the UI integration being different.

### Add OpenID Connect support

Add the [Microsoft.AspNetCore.Authentication.OpenIdConnect](https://www.nuget.org/packages/Microsoft.AspNetCore.Authentication.OpenIdConnect) Nuget packages to the ASP.NET Core project.

### Setup the OpenID Connect client

Add the authentication to the web application using the builder.Services in the **Program.cs** file. The configuration is dependent on the OpenID Connect server. Each OpenID Connect server requires small differences in the setup.

```csharp
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
var oidcConfig = builder.Configuration.GetSection("OpenIDConnectSettings");

options.Authority = oidcConfig["Authority"];
options.ClientId = oidcConfig["ClientId"];
options.ClientSecret = oidcConfig["ClientSecret"];

options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.ResponseType = OpenIdConnectResponseType.Code;

options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;

options.MapInboundClaims = false;
options.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;
options.TokenValidationParameters.RoleClaimType = "roles";
});
```

See [Secure an ASP.NET Core Blazor Web App with OpenID Connect (OIDC)](xref:blazor/security/blazor-web-app-oidc) for details on the different OpenID Connect options.

See [Mapping, customizing, and transforming claims in ASP.NET Core](xref:security/authentication/claims) for the different claims mapping possibilities.

> [!NOTE]
> The following namespaces are required:

```csharp
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
```

### Setup the configuration properties

Add the OpenID Connect client settings to the application configuration properties. The settings must match the client configuration in the OpenID Connect server. No secrets are persisted in the application settings, the secrets are stored in a Key Vault in production environments or in user secrets in a development environment.

```json
"OpenIDConnectSettings": {
// OpenID Connect URL
"Authority": "https://localhost:44318",
// client ID from the OpenID Connect server
"ClientId": "oidc-pkce-confidential",
//"ClientSecret": "--stored-in-user-secrets-or-key-vault--"
},
```

### Update the ASP.NET Core pipeline method in the program class.

The UseRouting must be implemented before the UseAuthorization method.

```csharp
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
// Authorization is applied for middleware after the UseAuthorization method
app.UseAuthorization();
app.MapRazorPages();
```

### Force authorization

Add the Authorize attribute to the protected razor pages, for example the Index.cshtml.cs file

```csharp
[Authorize]
```

A better way would be to force the whole application to be authorized and opt out for unsecure pages

```csharp
builder.Services.AddAuthorizationBuilder()
.SetFallbackPolicy(new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build());
```

### Add a new Logout.cshtml and SignedOut.cshtml Razor page to the project

A logout is required to sign-out both the cookie session and the OpenID Connect session. The whole application needs to redirect to the OpenID Connect server to sign-out. After a successful sign-out, the application will open the RedirectUri route.

Implement a default sign-out page and change the Logout razor page code with this:

```csharp
[Authorize]
public class LogoutModel : PageModel
{
public IActionResult OnGetAsync()
{
return SignOut(new AuthenticationProperties
{
RedirectUri = "/SignedOut"
},
CookieAuthenticationDefaults.AuthenticationScheme,
OpenIdConnectDefaults.AuthenticationScheme);
}
}
```

The `SignedOut.cshtml` requires the AllowAnonymous attribute.

```csharp
[AllowAnonymous]
public class SignedOutModel : PageModel
{
public void OnGet()
{
}
}
```

### Add a login, logout button for the user.

```
@if (Context.User.Identity!.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Logout">Logout</a>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@blowdart Do we care about protecting logout endpoints with anti-csrf tokens?

</li>

<span class="nav-link text-dark">Hi @Context.User.Identity.Name</span>
}
else
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-page="/Index">Login</a>
</li>
}
```

## Examples with code snippets

### Example Using User Info endpoint

The OpenID Connect options can be used to map claims, implement handlers or even save the tokens in the session for later usage.

The **Scope** option can be used to request different claims or a refresh token which is sent as information to the OpenID Connect server. Requesting the **offline_access** is asking the server to return a reference token which can be used to refresh the session without authenticating the user of the application again.

```csharp
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
var oidcConfig = builder.Configuration.GetSection("OpenIDConnectSettings");
options.Authority = oidcConfig["IdentityProviderUrl"];
options.ClientSecret = oidcConfig["ClientSecret"];
options.ClientId = oidcConfig["Audience"];
options.ResponseType = OpenIdConnectResponseType.Code;

options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("offline_access");

options.ClaimActions.Remove("amr");
options.ClaimActions.MapJsonKey("website", "website");

options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;

// .NET 9 feature
options.PushedAuthorizationBehavior = PushedAuthorizationBehavior.Require;

options.TokenValidationParameters.NameClaimType = JwtRegisteredClaimNames.Name;
options.TokenValidationParameters.RoleClaimType = "roles";
});
```

See the following code example:

https://github.com/damienbod/keycloak-backchannel/tree/main/RazorPagePar

### Implementing Microsoft identity providers

Microsoft has multiple identity providers and OpenID Connect implementations. Microsoft has different OpenID Connect servers:

* Microsoft Entra ID
* Microsoft Entra External ID
* Azure AD B2C

If authenticating using one of the Microsoft identity providers in ASP.NET Core, it is recommended to use the [Microsoft.Identity.Web](https://github.com/AzureAD/microsoft-identity-web) Nuget packages.

The Microsoft.Identity.Web Nuget packages is a Microsoft specific client built on top on the ASP.NET Core OpenID Connect client with some changes to the default client.

## Using third party OpenID Connect provider clients

Many OpenID Connect server implementations create Nuget packages which are optimized for the same OpenID Connect implementation. These packages implement the OpenID Connect client specifics with the extras required by the specific OpenID Connect server. Microsoft.Identity.Web is one example of this.

If implementing multiple OpenID Connect clients from different OpenID Connect servers in a single application, it is normally better to revert to the default ASP.NET Core implementation as the different clients overwrite some options which affect the other clients.

[OpenIddict Web providers](https://documentation.openiddict.com/integrations/web-providers) is a client implementation which supports many different server implementations.

[IdentityModel](https://github.com/IdentityModel/IdentityModel) is a .NET standard helper library for claims-based identity, OAuth 2.0 and OpenID Connect. This can also be used to help with the client implementation.

## Backend for frontend (BFF) security architecture

It is no longer recommended to implement OpenID Connect public clients for any web applications.

See the [draft OAuth 2.0 for Browser-Based Applications](https://datatracker.ietf.org/doc/draft-ietf-oauth-browser-based-apps/) for further details.

If implementing **web** applications which have no backend, it is recommended to use the [Backend for Frontend (BFF) pattern](/azure/architecture/patterns/backends-for-frontends) security architecture. This pattern can be implemented in different ways, but the authentication is always implemented in the backend and no sensitive data is sent to the web client for further authorization or authentication flows.

## Advanced features, standards, extending the OIDC client

### Logging

Debugging OpenID Connect clients can be hard. Personally identifiable information (PII) data is not logged by default. If debugging in development mode, the ** IdentityModelEventSource.ShowPII** can be used to log sensitive personal data. This should never by deployed to productive servers.

```csharp
//using ...

using Microsoft.IdentityModel.Logging;

var builder = WebApplication.CreateBuilder(args);

//... code

var app = builder.Build();

IdentityModelEventSource.ShowPII = true;

//... code

app.Run();
```

### OIDC and OAuth Parameter Customization

The OAuth and OIDC authentication handlers [`AdditionalAuthorizationParameters`](https://source.dot.net/#Microsoft.AspNetCore.Authentication.OAuth/OAuthOptions.cs,ddb988460467cfbf) option allows customization of authorization message parameters that are usually included as part of the redirect query string:

## Map claims from OpenID Connect

Refer to the following document:

[Mapping, customizing, and transforming claims in ASP.NET Core](xref:security/authentication/claims)

## Blazor OpenID Connect

Refer to the following document:

[Secure an ASP.NET Core Blazor Web App with OpenID Connect (OIDC)](xref:blazor/security/blazor-web-app-oidc)

## Standards

[OpenID Connect 1.0](https://openid.net/specs/openid-connect-core-1_0-final.html)

[Proof Key for Code Exchange by OAuth Public Clients](https://datatracker.ietf.org/doc/html/rfc7636)

[The OAuth 2.0 Authorization Framework](https://datatracker.ietf.org/doc/html/rfc6749)

[OAuth 2.0 Pushed Authorization Requests (PAR) RFC 9126](https://datatracker.ietf.org/doc/html/rfc9126)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
@page
@model ErrorModel
@{
ViewData["Title"] = "Error";
}

<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>

@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}

<h3>Development Mode</h3>
<p>
Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPageOidc.Pages;

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPageOidc.Pages;

[Authorize]
public class IndexModel : PageModel
{
public void OnGet()
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@page
@model RazorPageOidc.Pages.LogoutModel
@{
ViewData["Title"] = "Logout";
}

<h1>Logout</h1>

Loading
Loading