【发布时间】:2020-12-12 20:13:11
【问题描述】:
我目前正在为访问令牌的生命周期而苦苦挣扎。我有 dotnet core Web 应用程序和 dotnet core Web API。
Web 应用程序受到 OpenIDConnect 授权的保护。一旦您尝试连接到 Web 应用程序,您将被重定向到 Microsoft 登录表单,并在成功登录后,提供 Access Token 并将其与 Refresh Token 一起存储到 cookie 中。
因此,访问令牌在我的 WebAPI 请求的授权标头中传递。 当 access_token 生命周期到期时,我的 WebAPI 开始返回 401 Unauthorized。
我看了很多关于使用刷新令牌撤销访问令牌的文章,但我没有找到任何实现示例,所以我求助于你们。
这就是我在 Web 客户端中设置 OpenId 的方式。
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();
这就是我在 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;
});
最后,这是我的 ApiService 的构造函数,我在其中向标头添加访问令牌。
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);
}
如果您需要更多信息,请告诉我,我会提供。谢谢!
【问题讨论】:
-
只是为了正确理解:首先 - 您从 ASP .NET Core Web App 调用 ASP .NET Core Web API。第二个问题 - 您想为特定用户正确撤销刷新令牌吗?
-
1) 正确 2) 我想通过使用刷新令牌来撤销访问令牌(授权代码流程原则)但是经过几次搜索后,这似乎是一个内置功能。所以我不确定这是否能解决我的问题。
-
@DanielRusnok 我已经编辑了标题以反映您的 cmets,如果这不正确,请随时将其改回
-
@DanielRusnok 没错,但从我们现在的讨论来看,我认为您的问题的答案在这里:stackoverflow.com/questions/48952087/… 您可以使用 MSAL 来刷新令牌。也检查一下 - 这是解释:github.com/AzureAD/microsoft-authentication-library-for-dotnet/…
标签: azure authentication azure-active-directory access-token refresh-token