ASP.NET Core v2.x

This tutorial demonstrates how to add user login to an ASP.NET Core 2.x application.

Four steps are required to complete your first test login:

  1. Register your application in Criipto Verify
  2. Configure your OAuth2 flow
  3. Configure your application to use Criipto Verify
  4. 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 App

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.

Callback URLs

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 creating a new application you must first save the configuration.

Once you have a saved application registration you are ready to configure the OAuth2 code flow. Open the application registration and configure it for the right OAuth2 flow:

  1. Enable OAuth2 code flow
  2. Copy the generated client secret.
  3. Set the user info response strategy to plainJson to enable retrieval of plain JSON user information from the /oauth2/userinfo endpoint.

OAuth2 code flow

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.

OAuth2 code flow

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.

For more on how to make it work in an iframe using the postMessage() functionality please check our guide to iframed authentication.

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 2.2, 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.

Install-Package Microsoft.AspNetCore.Authentication.Cookies
Install-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().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

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 AcrValues 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:

Norwegian BankID  
  Mobile: urn:grn:authn:no:bankid:mobile
  Hardware token (kodebrikke):  urn:grn:authn:no:bankid:central
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:tupas
  Mobile certificate (Mobiilivarmenne):  urn:grn:authn:fi:mobile-id
  Any of the two: urn:grn:authn:fi:all

  

Enable the OpenID Connect middleware

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

// Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{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:

  1. 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
  2. The user picks the login method, or the application is hardcoded to one of the authentication options
  3. A request for a resource protected by the [Authorization] kicks off the OIDC middleware login flow
  4. The user’s browser is redirected to the Criipto Verify service where actual login happens
  5. A callback with an issued authorization code is sent back to the application and intercepted by the OIDC middleware
  6. 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
  7. 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.