Accessing the OIDC tokens in ASP.NET Core 2.0

In ASP.NET Core 1.1

So, for example, in ASP.NET Core 1.x, if you wanted to access the tokens (id_token, access_token and refresh_token) from your application, you could set the SaveTokens property when registering the OIDC middleware:

1
2
3
4
5
6
7
8
// Inside your Configure method
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions("Auth0")
{
    // Set all your OIDC options...
    // and then set SaveTokens to save tokens to the AuthenticationProperties
    SaveTokens = true
});

You would then subsequently be able to retrieve those tokens by calling GetAuthenticateInfoAsync inside your controllers, and using the result to retreive the tokens, for example:

1
2
3
4
5
6
7
// Inside on of your controllers
if (User.Identity.IsAuthenticated)
{
    var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Auth0");
    string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];
    string idToken = authenticateInfo.Properties.Items[".Token.id_token"];
}
1

In ASP.NET Core 2.0

In ASP.NET Core 2.0 this has changed. Firstly, you now register your OIDC middleware inside ConfigureServices as follows (making sure to set SaveTokens to true):

1
2
3
4
5
6
7
8
9
10
11
12
13
// Inside your ConfigureServices method
services.AddAuthentication(options => {
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options => {
    // Set all your OIDC options...
    // and then set SaveTokens to save tokens to the AuthenticationProperties
    options.SaveTokens = true;
});

You would then subsequently be able to retrieve those tokens by calling GetTokenAsync for each of the tokens you want to access. The code sample below shows how to access the access_token and the id_token:

1
2
3
4
5
6
7
8
9
// Inside on of your controllers
if (User.Identity.IsAuthenticated)
{
    string accessToken = await HttpContext.GetTokenAsync("access_token");
    string idToken = await HttpContext.GetTokenAsync("id_token");
    // Now you can use them. For more info on when and how to use the
    // access_token and id_token, see https://auth0.com/docs/tokens
}

Happy coding!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.