ASP.NET .NET 6 OIDC Retrieve JWT AccessToken after SaveTokens
I was not able to find the docs for retrieving the JWT AccessToken in ASP.NET .NET 6 after they are saved so I decided to document it here.
You may be familiar with the HttpContext.GetTokenAsync() method. This appears to have worked in previous version of .NET, but I could not get it to work in .NET 6.
First, make sure you are saving the access tokens in the AddOpenIdConnect configuration.
builder
.Services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SaveTokens = true;
});
Then, instead of HttpContext.GetTokenAsync(), call HttpContext.AuthenticateAsync(), and get the token out of the AuthenticateResult.
var accessToken = authenticateResult?.Properties?.GetString(".Token.access_token");
Hope this helps,
Aaron
Aaron
Comments