Authentication in ASP.NET Core v3.x
This tutorial demonstrates how to add user login to the existing ASP.NET Core 3.x application. If you are migrating .NET Core v2.x application to .NET Core v3.1, skip to the Migrate .NET Core v2.x sample to .NET Core v3.1 section.
Four steps are required to complete your first test login:
- Register your application in Criipto Verify
- Configure your OAuth2 flow
- Configure your application to use Criipto Verify
- Trigger authentication in your application
This explains how to set up your application and test with test users. To use real e-IDs for login the setup is the same, but you must be set up for Production
And note that you need test e-ID users to see your code in action. How to get those is described further down.
You may get a completed and ready to run sample from GitHub showing the below recipe in the simplest of ASP.NET Core MVC applications.
To modify your existing application to work with Criipto Verify follow the steps below.
Register Your Application in Criipto Verify
After you signed up for Criipto Verify, you must register an application before you can actually try logging in with any e-ID.
Once you register your application you will also need some of the information for communicating with Criipto Verify. You get these details from the settings of the application in the dashboard.
Specifically you need the following information to configure you application
- Client ID to identify you application to Criipto Verify. In the case below we chose
urn:criipto:samples:no1
- Domain on which you will be communicating with Criipto Verify. Could be for example
samples.criipto.id
Register callback URLs
Before you can start sending authentication requests to Criipto Verify you need to register the URLs on which you want to receive the returned JSON Web Token, JWT.
The Callback URL of your application is the URL where Criipto Verify will redirect to after the user has authenticated in order for the OpenID Connect ASP.NET 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 sample project project is https://localhost:5001/callback and http://localhost:5000/callback, so be sure to add this to the Callback URLs section of your application. Put each URL on a new line.
If you deploy your application to a different URL you will also need to ensure to add that URL to the Callback URLs.
Configure the OAuth2 code flow
If you are registering a new application, you must first save the configuration.
Once you have a saved application registration you may configure the OAuth2 code flow.
Open the application registration and configure it for the right OAuth2 flow:
- Enable OAuth2 code flow
- Copy the generated client secret.
- Set the user info response strategy to
plainJson
to enable retrieval of plain JSON user information from the/oauth2/userinfo
endpoint.
Note that this is the only time you will be shown the actual value of the client secret. Criipto only stores this as a hashed value, which means you cannot retieve the value once it has been generated and stored.
You may configure Criipto Verify to retrieve the user information from either the userinfo
endpoint - the default option - or you may explicitely choose the fromTokenEndpoint
in the user info response strategy instead:
Configure Your Application to Use Criipto Verify
Most of the e-ID services supported by Criipto are suited for iframe integration into your web pages. The approach described here does not make any assumptions about that, but simply shows how to enable Criipto Verify authentication in a web application.
Install dependencies
To integrate Criipto Verify with ASP.NET Core you will use the Cookie and OpenID Connect (OIDC) authentication handlers. The seed project already references the ASP.NET Core meta package (Microsoft.AspNetCore.App) which includes all NuGet packages shipped by Microsoft as part of ASP.NET Core 3.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 meta package, then please make sure that you add the Microsoft.AspNetCore.Authentication.Cookies and Microsoft.AspNetCore.Authentication.OpenIdConnect packages to your application.
dotnet add package Microsoft.AspNetCore.Authentication.Cookies
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect
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
. Configure the necessary parameters, such as ClientId
, ClientSecret
, ResponseType
, and not least the Authority
. The latter is used by the middleware to get the metadata describing the relevant endpoints, the signing keys etc.
The OIDC middleware requests both the openid
and profile
scopes by default, but note that Criipto Verify by nature returns only the information derived from the underlying e-ID service. Changing the scopes does not affect the amount and nature of information delivered from the user information endpoint.
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options => {
options.ClientId = Configuration["Criipto:ClientId"]; // ClientID from application registration
options.ClientSecret = Configuration["Criipto:ClientSecret"]; // Client from application registration
options.Authority = $"https://{Configuration["Criipto:Domain"]}/"; // Domain from application registration
options.ResponseType = "code";
// The next to settings must match the Callback URLs in Criipto Verify
options.CallbackPath = new PathString("/callback");
options.SignedOutCallbackPath = new PathString("/signout");
// Hook up an event handler to set the acr_value of the authorize request
// In a real world implementation this is probably a bit more flexible
options.Events = new OpenIdConnectEvents() {
OnRedirectToIdentityProvider = context => {
context.ProtocolMessage.AcrValues = context.Request.Query["loginmethod"];
return Task.FromResult(0);
}
};
});
services.AddMvc();
}
Note that the above code dynamically sets the AcrValues
by picking it from the query string. In the general case, this may, of course, be set in other ways. Just note that it is dynamically set at the time of the actual login.
Choosing the specific login method
Criipto Verify supports a range of country and bank specific e-ID services. They are all accessed through the same endpoints, e.g. https://<YOUR COMPANY>.criipto.id/oauth2/authorize
To pick the login method you must set the acr_values
parameter on the authentication request in order to choose the type of authentication you want. How you set this query string parameter varies with programming platform and your OpenID Connect library of choice.
The current list of possible values is:
Login method | acr_values |
---|---|
Norwegian BankID | |
Mobile or Web (user choice): | urn:grn:authn:no:bankid |
Norwegian Vipps Login | |
Login with Vipps app: | urn:grn:authn:no:vipps |
Swedish BankID | |
Same device: | urn:grn:authn:se:bankid:same-device |
Another device (aka mobile): | urn:grn:authn:se:bankid:another-device |
Danish NemID | |
Personal with code card: | urn:grn:authn:dk:nemid:poces |
Employee with code card: | urn:grn:authn:dk:nemid:moces |
Employee with code file: | urn:grn:authn:dk:nemid:moces:codefile |
Finish e-ID | |
BankID: | urn:grn:authn:fi:bank-id |
Mobile certificate (Mobiilivarmenne): | urn:grn:authn:fi:mobile-id |
Any of the two: | urn:grn:authn:fi:all |
Itsme | |
Basic: | urn:grn:authn:itsme:basic |
Advanced: | urn:grn:authn:itsme:advanced |
Belgium | |
Verified e-ID | urn:grn:authn:be:eid:verified |
Germany | |
Sofort (with Schufa check) | urn:grn:authn:de:sofort |
Enable the OpenID Connect middleware
Next, add the authentication middleware. In the Configure
method of the Startup
class, call the UseAuthentication
and UseAuthorization
method. Make sure to call UseAuthentication
method before UseAuthorization
method, but both after UseRouting
method.
// Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(routes =>
{
routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
Trigger Login and Logout in Your Application
After the middleware for performing the authentication is wired up, the next step is to perform the actual authentication.
Protected resources trigger login
One way to trigger the authentication flow is to tag routes in ASP.NET MVC with the Authorize
. This is a way of telling the framework to only allow requests from authenticated users.
[Authorize] // If not already authenticated, this kicks off the process
public IActionResult Protected()
{
return View();
}
Note that you may plug in your own Authorization handlers derived from Microsoft.AspNetCore.Authorization.AuthorizationHandler<TRequirement>
to add additional guards beyond just authentication.
Explicit logout
Logout requires both terminating the local session by removing the cookies as well as telling Criipto Verify that the session is over.
public async Task Logout()
{
// Call the server to terminate the session
await HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
// Remove authnetication cookies
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
Test users
Almost all e-ID types have a notion of test users and real users.
Real users are real people logging in to a web site, thus voluntering their real name and typically also a social security number, SSN.
Test users are either created by you for the occasion, or we provide you with access to already created test users.
You may ready more in the section on test users
The runtime flow
In summary, the steps above will lead to a runtime flow looks like this:
- The web server starts the application which configures and initializes the OpenID Connect middleware. The middleware is configured with a URL from which it retrieves the metadata describing the various endpoints and encryption keys, such as the token and userinfo endpoints as well the token signing certificates
- The user picks the login method, or the application is hardcoded to one of the authentication options
- A request for a resource protected by the
[Authorization]
kicks off the OIDC middleware login flow - The user’s browser is redirected to the Criipto Verify service where actual login happens
- A callback with an issued authorization code is sent back to the application and intercepted by the OIDC middleware
- The middleware calls the Criipto Verify service to exchange the code for an access token. Note that this is a direct server to server call which - unlike the other communication - does not pass through the browser
- The access token is used by the OIDC middleware to retrieve the available user information which is set as claims on the user principal.
If you want to inspect what is actually going on you may see much of it if you use for example chrome and turn on the developer tools to inspect the network traffic.
Setting up for Production
Once you have integrated with Criipto Verify and tested that it works with test user accounts, you are ready to go to production to accept real e-ID logins and signatures.
Please note that for production usage a paid subscription is required.
Read more in the section on how to set up for production.
Migrate ASP.NET Core v2.x sample to v3.x
This section demonstrates how to migrate ASP.NET Core v2.x sample from GitHub to ASP.NET Core v3.1
Before proceeding, make sure you have the appropriate ASP.NET Core 3.1 SDK.
Following steps are required to complete your first test login:
Modify aspnetcore-oidc project file
- Change the
TargetFramework
fromnetcoreapp2.2
tonetcoreapp3.1
. - Remove the following line from the
PropertyGroup
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
- Remove following
PackageReference
entries fromItemGroup
<PackageReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
- Add following
PackageReference
entries to theItemGroup
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.1" />
Restore dependencies
Restore dependencies to make sure they are compatible with a new version of .NET Core.
Run the following command:
dotnet restore
Modify Startup.cs file
- In the
ConfigureServices
method, remove theSetCompatibilityVersion
method. Change the lineservices.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
into
services.AddMvc();
- In the
Configure
method, change the second argument’s type fromIHostingEnvironment
toIWebHostEnvironment
. - Add the following
using
using Microsoft.Extensions.Hosting;
- Add
app.UseRouting();
beforeapp.UseAuthentication();
. - Add
app.UseAuthorization();
afterapp.UseAuthentication();
. - Replace the following code from the
Configure
methodapp.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
with
app.UseEndpoints(routes => { routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); });