Integrations
Accept MitID, Swedish BankID, Norwegian BankID and other eID logins with ASP.NET Core 3.1 and Criipto Verify
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:
This explains how to set up your application and test with test users. To use real eIDs for login the setup is the same, but you must be set up for Production
And note that you need test eID 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.
After you signed up for Criipto Verify, you must register an application before you can actually try logging in with any eID.
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
urn:criipto:samples:no1
samples.criipto.id
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 these URLs to the list of allowed URLs for your application:
https://localhost:5001/callback
http://localhost:5000/callback
https://localhost:5001/signout
http://localhost:5000/signout
If you deploy your application to a different URL you will also need to ensure to add that URL to the Callback URLs.
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:
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 retrieve the value once it has been generated and stored.
Some libraries do not support the final userinfo
request. In those cases you will need to fetch the user data directly from the token
endpoint as opposed to the userinfo
endpoint. Do this by choosing the appropriate option as shown below.
You may configure Criipto Verify to retrieve the user information from either the userinfo
endpoint - the default option - or you may explicitly choose the fromTokenEndpoint
in the user info response strategy instead:
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
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 eID 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 secret from oauth2 code flow
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.
Login method | acr_values | base64 encoded |
---|---|---|
Norwegian BankID | ||
Mobile or Web (user choice): | urn:grn:authn:no:bankid | dXJuOmdybjphdXRobjpubzpiYW5raWQ= |
BankID Biometrics (level substantial): | urn:grn:authn:no:bankid:substantial | dXJuOmdybjphdXRobjpubzpiYW5raWQ6c3Vic3RhbnRpYWw= |
Norwegian Vipps Login | ||
Login with Vipps app: | urn:grn:authn:no:vipps | dXJuOmdybjphdXRobjpubzp2aXBwcw== |
Swedish BankID | ||
All options (user chooses): | urn:grn:authn:se:bankid | dXJuOmdybjphdXRobjpzZTpiYW5raWQ= |
Same device: | urn:grn:authn:se:bankid:same-device | dXJuOmdybjphdXRobjpzZTpiYW5raWQ6c2FtZS1kZXZpY2U= |
Another device (aka mobile): | urn:grn:authn:se:bankid:another-device | dXJuOmdybjphdXRobjpzZTpiYW5raWQ6YW5vdGhlci1kZXZpY2U= |
QR code: | urn:grn:authn:se:bankid:another-device:qr | dXJuOmdybjphdXRobjpzZTpiYW5raWQ6YW5vdGhlci1kZXZpY2U6cXI= |
Danish MitID | ||
Level low: | urn:grn:authn:dk:mitid:low | dXJuOmdybjphdXRobjpkazptaXRpZDpsb3c= |
Level substantial: | urn:grn:authn:dk:mitid:substantial | dXJuOmdybjphdXRobjpkazptaXRpZDpzdWJzdGFudGlhbA== |
MitID Erhverv (MitID Business): | urn:grn:authn:dk:mitid:business | dXJuOmdybjphdXRobjpkazptaXRpZDpidXNpbmVzcw== |
Finnish Trust Network | ||
BankID: | urn:grn:authn:fi:bankid | dXJuOmdybjphdXRobjpmaTpiYW5raWQ= |
Mobile certificate (Mobiilivarmenne): | urn:grn:authn:fi:mobile-id | dXJuOmdybjphdXRobjpmaTptb2JpbGUtaWQ= |
Both of the above: | urn:grn:authn:fi:all | dXJuOmdybjphdXRobjpmaTphbGw= |
Itsme | ||
Basic: | urn:grn:authn:itsme:basic | dXJuOmdybjphdXRobjppdHNtZTpiYXNpYw== |
Advanced: | urn:grn:authn:itsme:advanced | dXJuOmdybjphdXRobjppdHNtZTphZHZhbmNlZA== |
Belgium | ||
Verified e-ID: | urn:grn:authn:be:eid:verified | dXJuOmdybjphdXRobjpiZTplaWQ6dmVyaWZpZWQ= |
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?}");
});
}
After the middleware for performing the authentication is wired up, the next step is to perform the actual authentication.
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.
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);
}
Almost all eID 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 read more in the section on eIDs
In summary, the steps above will lead to a runtime flow looks like this:
[Authorization]
kicks off the OIDC middleware login flowIf 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.
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 eID 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.
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:
Change the TargetFramework
from netcoreapp2.2
to netcoreapp3.1
.
Remove the following line from the PropertyGroup
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
Remove following PackageReference
entries from ItemGroup
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
Add following PackageReference
entries to the ItemGroup
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.1" />
Restore dependencies to make sure they are compatible with a new version of .NET Core.
Run the following command:
dotnet restore
In the ConfigureServices
method, remove the SetCompatibilityVersion
method. Change the line
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
into
services.AddMvc();
In the Configure
method, change the second argument's type from IHostingEnvironment
to IWebHostEnvironment
.
Add the following using
using Microsoft.Extensions.Hosting;
Add app.UseRouting();
before app.UseAuthentication();
.
Add app.UseAuthorization();
after app.UseAuthentication();
.
Replace the following code from the Configure
method
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
with
app.UseEndpoints(routes =>
{
routes.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});