ASP.NET Core v2.1: Login

View on Github

ASP.NET Core v2.1: Login

Gravatar for
By Damien Guard

This tutorial demonstrates how to add user login to an ASP.NET Core 2.x application. We recommend you to Log in to follow this quickstart with examples configured for your account.

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it out on Github.

View on Github
System requirements: .NET Core SDK 2.1.300 | .NET Core 2.1.0 | ASP.NET Core 2.1.0 | Visual Studio 2017 15.7 or Visual Studio Code (Optional)

Configure Auth0

Get Your Application Keys

When you signed up for Auth0, a new application was created for you, or you could have created a new one.

You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.

You need the following information:

  • Domain
  • Client ID
  • Client Secret

If you download the sample from the top of this page these details are filled out for you.

If you have more than one application in your account, the sample comes with the values for your Default App.

App Dashboard

Configure Callback URLs

The Callback URL of your application is the URL where Auth0 will redirect to after the user has authenticated in order for the OpenID Connect middleware to complete the authentication process.

You will need to add this URL to the list of Allowed URLs for your application. The Callback URL for the seed project is http://localhost:3000/callback, so be sure to add this to the Allowed Callback URLs section of your application.

If you deploy your application to a different URL you will also need to ensure to add that URL to the Allowed Callback URLs. For ASP.NET Core this URL will take the format http://YOUR_APPLICATION_URL/callback.

Configure Logout URLs

A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo query parameter.

The logout URL for your app must be whitelisted in the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.

If you are following along with the sample project you downloaded from the top of this page, the logout URL you need to whitelist in the Allowed Logout URLs field is http://localhost:3000.

Configure JSON Web Token Signature Algorithm

The ASP.NET Core OpenID Connect (OIDC) middleware which will be used to authenticate the user, requires that the JSON Web Token (JWT) be signed with an asymmetric key. To configure this go to the settings for your application in the Auth0 Dashboard, scroll down and click on Show Advanced Settings. Go to the OAuth tab and set the JsonWebToken Signature Algorithm to RS256.

Save your changes.

Configure your application to use Auth0

Universal Login is the easiest way to set up authentication in your application. We recommend using it for the best experience, best security and the fullest array of features. This guide will use it to provide a way for your users to log in to your ASP.NET Core application.

You can also create a custom login for prompting the user for their username and password. To learn how to do this in your application, follow the Custom Login sample.

Install dependencies

To integrate Auth0 with ASP.NET Core you will use the Cookie and OpenID Connect (OIDC) authentication handlers. The seed project already references the ASP.NET Core metapackage (Microsoft.AspNetCore.App) which includes all NuGet packages shipped by Microsoft as part of ASP.NET Core 2.1, including the packages for the Cookie and OIDC authentication handlers.

If you are adding this to your own existing project, and you have not referenced the metapackage, then please make sure that you add the Microsoft.AspNetCore.Authentication.Cookies and Microsoft.AspNetCore.Authentication.OpenIdConnect packages to your application.

Install and configure OpenID Connect Middleware

To enable authentication in your ASP.NET Core application, use the OpenID Connect (OIDC) middleware. Go to the ConfigureServices method of your Startup class. To add the authentication services, call the AddAuthentication method. To enable cookie authentication, call the AddCookie method.

Next, configure the OIDC authentication handler. Add a call to AddOpenIdConnect. To configure the authentication scheme, pass "Auth0" as the authenticationScheme parameter. You will use this value later to challenge the OIDC middleware.

Configure other parameters, such as ClientId, ClientSecret or ResponseType.

By default, the OIDC middleware requests both the openid and profile scopes. Because of that, you may get a large ID Token in return. We suggest that you ask only for the scopes you need. You can read more about requesting additional scopes in the User Profile step.

In the code sample below, only the openid scope is requested.

Next, add the authentication middleware. In the Configure method of the Startup class, call the UseAuthentication method.

Obtain an Access Token for Calling an API

If you want to call an API from your MVC application, you need to obtain an Access Token issued for the API you want to call. To obtain the token, pass an additional audience parameter containing the API identifier to the Auth0 authorization endpoint.

In the configuration for the OpenIdConnectOptions object, handle the OnRedirectToIdentityProvider event and add the audience parameter to ProtocolMessage.

Trigger authentication

Add the Login and Logout Methods

Add the Login and Logout actions to AccountController.

To add the Login action, call ChallengeAsync and pass "Auth0" as the authentication scheme. This will invoke the OIDC authentication handler you registered in the ConfigureServices method.

After the OIDC middleware signs the user in, the user is also automatically signed in to the cookie middleware. This allows the user to be authenticated on subsequent requests.

For the Logout action, you need to sign the user out of both middlewares.

The RedirectUri passed in both instances indicates where the user is redirected after they log in or fail to log in.

ASP.NET Core calls SignOutAsync for the "Auth0" authentication scheme. You need to provide the OIDC middleware with the URL for logging the user out of Auth0. To set the URL, handle the OnRedirectToIdentityProviderForSignOut event when you register the OIDC authentication handler.

When the application calls SignOutAsync for the OIDC middleware, it also calls the /v2/logout endpoint of the Auth0 Authentication API. The user is logged out of Auth0.

If you specify the returnTo parameter, the users will be redirected there after they are logged out. Specify the URL for redirecting users in the Allowed Logout URLs field in your Application Settings.

In the Startup.cs file, update the call to AddOpenIdConnect with the following code:

Add the Log In and Log Out Buttons

Add the Log In and Log Out buttons to the navigation bar. In the /Views/Shared/_Layout.cshtml file, in the navigation bar section, add code that displays the Log Out button when the user is authenticated and the Log In button if not. The buttons link to the Logout and Login actions in the AccountController:

Run the Application

When the user selects the Log In button, the OIDC middleware redirects them to the hosted version of the Lock widget in your Auth0 domain.

About the login flow

  1. The user clicks on the Log In button and is directed to the Login route.
  2. The ChallengeAsync tells the ASP.NET authentication middleware to issue a challenge to the authentication handler registered with the Auth0 authenticationScheme parameter. The parameter uses the "Auth0" value you passed in the call to AddOpenIdConnect in the Startup class.
  3. The OIDC handler redirects the user to the Auth0 /authorize endpoint, which displays the Lock widget. The user can log in with their username and password, social provider or any other identity provider.
  4. Once the user has logged in, Auth0 calls back to the /callback endpoint in your application and passes along an authorization code.
  5. The OIDC handler intercepts requests made to the /callback path.
  6. The handler looks for the authorization code, which Auth0 sent in the query string.
  7. The OIDC handler calls the /oauth/token endpoint to exchange the authorization code for the user's ID and Access Tokens.
  8. The OIDC middleware extracts the user information from the claims on the ID Token.
  9. The OIDC middleware returns a successful authentication response and a cookie which indicates that the user is authenticated. The cookie contains claims with the user's information. The cookie is stored, so that the cookie middleware will automatically authenticate the user on any future requests. The OIDC middleware receives no more requests, unless it is explicitly challenged.

Store the Tokens

The OIDC middleware in ASP.NET Core automatically decodes the ID Token returned from Auth0 and adds the claims from the ID Token as claims in the ClaimsIdentity. This means that you can use User.Claims.FirstOrDefault("<claim type>").Value to obtain the value of any claim inside any action in your controllers.

The seed project contains a controller action and view that display the claims associated with a user. Once a user has logged in, you can go to /Account/Claims to see these claims.

You may want to Access Tokens received from Auth0. For example, you can use the Access Token to authenticate the user in calls to your API. To achieve this, when calling AddOpenIdConnect, set the SaveTokens property to true. This saves the tokens to AuthenticationProperties:

To retrieve the tokens, you can call GetTokenAsync:

For general information on using APIs with web applications, see the Authorization Code Flow article.

Use Auth0 for FREE