I'm currently struggling with access token lifetime. I have dotnet core Web Application and dotnet core Web API.
The web application is protected with OpenIDConnect authorization. Once you try to connect into web app, you are redirected to Microsoft login form and after successful login, the Access Token is provided and stored into cookie together with Refresh Token.
Therefore, the Access Token is passed in Authorization Header for my WebAPI request. When the access_token lifetime expires, then my WebAPI starts to return 401 Unauthorized.
I read a lot articles about revoking access token by using refresh token, but I didn't find any implementation example, so I turn to you guys.
This is how I am setting up the OpenId in Web Client.
services.AddDataProtection();
services.AddAuthorization();
services.AddWebEncoders();
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.ClientId = Configuration["AzureAd:ClientId"];
options.Authority = $"{Configuration["AzureAd:AadInstance"]}{Configuration["AzureAd:Tenant"]}/v2.0";
options.ClientSecret = Configuration["AzureAd:ClientSecret"];
options.ResponseType = "code";
options.SaveTokens = true;
options.UseTokenLifetime = true;
options.Scope.Add(Configuration["AzureAd:Scope"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = Configuration["AzureAd:Tenant"] != "common",
RoleClaimType = JwtClaimTypes.Role
};
options.Events = new OpenIdConnectEvents
{
OnRemoteFailure = context =>
{
context.HandleResponse();
context.Response.Redirect("/error");
return Task.CompletedTask;
}
};
});
services.AddHttpContextAccessor();
This is how I am setting up authentication in Web API Startup.cs.
services.AddAuthentication("Bearer")
.AddJwtBearer(
"Bearer",
options =>
{
options.Authority = $"{Configuration["AzureAd:AadInstance"]}{Configuration["AzureAd:Tenant"]}/v2.0";
options.Audience = Configuration["AzureAd:Audience"];
options.TokenValidationParameters.ValidateIssuer = false;
});
And lastly, this is constructor of my ApiService, where I am adding access token to headers.
protected ApiService(HttpClient httpClient, string apiUri, IHttpContextAccessor httpContextAccessor, ILogger<ApiService> logger)
{
this.httpClient = httpClient;
this.apiUri = apiUri;
this.logger = logger;
context = httpContextAccessor.HttpContext;
this.httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer", context.GetTokenAsync("access_token").Result);
}
If you need guys any more information, tell me and I will provided it. Thank you!