Authorization code flow in asp.net core and Is4 - jwt and cookies

Viewed 54

I have simply basic solution for asp.net core web app and Is4.

In asp.net core I use addCookies() method, but the is4 returns me jwt token, why there is jwt when I use cookies?

I figure out it when I call

HttpContext.getTokenAsync(openIdconnectparameterNames.idToken)

Here I get jwt.. Can someone explain me why I get JWT if I'm using cookies?

1 Answers

I will try to explain how authentication using OpenId Connect Authorization Code flow is usually implemented for an asp.net core web app.

When an unauthenticated user (no cookie) tries to access your web app, the web app initiates the authorization code flow in order to authenticate the user. During the flow, the user is prompted to log in and then at some point, if login was successful, the identity provider (IdentityServer4) sends an ID token and an access token to the web app as you can also see in the diagram below:

Authorization Code Flow

The ID token contains user profile information. This is how the web app knows which user logged in. The access token can be used to get additional user information by calling the User Info Endpoint of Identity Server. Now the web app creates a cookie that contain all necessary user information, so that the next time he tries to access the web app, it won't have to initiate the whole authorization flow again. The web app will be able to identify if user is authenticated by validating the cookie.

The whole id token and access token are saved inside the cookie if you set SaveToken property to true in AddOpenIdConnect options.

services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
    //...
    // access token is needed to make this request to identity server
    options.GetClaimsFromUserInfoEndpoint = true;

    options.SaveTokens = true;
});

Then you can read the tokens from cookie using

var accessToken = await HttpContext.GetTokenAsync("access_token");
var idToken = await HttpContext.GetTokenAsync("id_token");

Saving the tokens in the cookie is not necessary and you shouldn't do it if you don't need the tokens anymore after authentication (for example you might need the access token to access an API: https://docs.identityserver.io/en/latest/quickstarts/3_aspnetcore_and_apis.html).

https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow

Related