【发布时间】:2018-09-23 19:14:33
【问题描述】:
上周我正在尝试配置 IdentityServer4 以获取自动更新的访问令牌。
我有一个 API:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5100";
options.RequireHttpsMetadata = false;
options.ApiName = "api1";
});
我的 MVC 客户端配置:
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5100";
options.RequireHttpsMetadata = false;
options.ClientId = "mvc";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
options.Scope.Add("offline_access");
});
以及 IdentityServer 的客户端配置:
return new List<Client>
{
new Client
{
ClientId = "mvc",
ClientName = "My mvc",
AllowedGrantTypes = GrantTypes.Hybrid,
RequireConsent = false,
AccessTokenLifetime = 10,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:5102/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5102/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.OfflineAccess,
"api1"
},
AllowOfflineAccess = true
}
};
在客户端,我使用 AJAX 查询调用 API 来获取/发布/放置/删除数据。我将访问令牌添加到请求中并获得结果。
private async getAuthenticationHeader(): Promise<any> {
return axios.get('/token').then((response: any) => {
return { headers: { Authorization: `Bearer ${response.data}` } };
});
}
async getAsync<T>(url: string): Promise<T> {
return this.httpClient
.get(url, await this.getAuthenticationHeader())
.then((response: any) => response.data as T)
.catch((err: Error) => {
console.error(err);
throw err;
});
}
访问令牌由MVC客户端方法提供:
[HttpGet("token")]
public async Task<string> GetAccessTokenAsync()
{
//todo DoronkinDY: Cache and clear when token expired
return await HttpContext.GetTokenAsync("access_token");
}
它工作正常。访问令牌过期后(在我的情况下,由于倾斜,它发生在 10 秒和 5 分钟后)我在客户端收到 401,所以如果有机会在访问令牌过期时自动更新访问令牌,那就太好了。
根据我认为的文档,可以通过将 AllowOfflineAccess 设置为 true 并添加合适的范围“offline_access”来实现。
也许我不了解访问和刷新令牌使用的正确流程。我可以自动完成还是不可能?我想,我们可以在查询中使用刷新令牌,但我不明白如何。
我已经阅读了很多 SO 答案和 github 问题,但我仍然感到困惑。你能帮我弄清楚吗?
【问题讨论】:
-
“我已经阅读了很多这样的答案” 也许你可以链接到其中的一些,以避免任何人将其标记为重复,如果他们没有帮不了你。 ;)
-
感谢您对 SO 问题的通知,我找到了合适的:stackoverflow.com/questions/44175115/…
-
我已经实现了第二种方法。我的解决方案包括检查访问令牌的过期时间,如果不到 1 分钟 - 更新访问令牌。
标签: access-token identityserver4 refresh-token