我有一个Blazor Web应用程序,它连接到其他Identity Server 4服务器。我可以使登录名正常工作,并将访问令牌传递回Blazor。但是,当令牌过期时,我不知道如何去获取新的访问令牌?我应该获取刷新令牌,然后获取访问令牌吗?我对这一切的工作方式感到困惑。
blazor码
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = AzureADDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(AzureADDefaults.AuthenticationScheme,options =>
{
options.Authority = "https://localhost:44382";
options.RequireHttpsMetadata = true;
options.ClientId = "client";
options.ClientSecret = "secret";
options.ResponseType = "code id_token token";
options.SaveTokens = true;
options.Scope.Add("IdentityServerApi");
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("email");
options.Scope.Add("roles");
options.Scope.Add("offline_access");
});
IdentityServer4设置
...
new Client
{
ClientId = "client",ClientSecrets = { new Secret("secret".Sha256()) },AllowedGrantTypes = GrantTypes.Hybrid,AllowaccessTokensViaBrowser = true,RequireclientSecret = true,RequireConsent = false,Redirecturis = { "https://localhost:44370/signin-oidc" },PostLogoutRedirecturis = { "https://localhost:44370/signout-callback-oidc" },AllowedScopes = { "openid","profile","email","roles","offline_access",IdentityServerConstants.LocalApi.ScopeName
},AllowedCorsOrigins = { "https://localhost:44370" },AlwaysSendClientClaims = true,AlwaysIncludeUserClaimsInIdToken = true,AllowOfflineaccess = true,accessTokenLifetime = 1,//testing
UpdateaccessTokenClaimsOnRefresh = true
},...
更新:
我已将客户端和服务器的代码更新为offline_access(感谢下面的更新)。我的下一个问题是,由于访问令牌过期而被拒绝后,如何在Blazor中注入刷新令牌的请求?
我有Blazor应用程序回调API(用于验证访问令牌)。
public class APIClient : IAPIClient
{
private readonly HttpClient _httpClient;
//add the bearer token to the APIClient when the client is used
public APIClient(IHttpContextaccessor httpaccessor,HttpClient client,IConfiguration configuration)
{
var accessToken = httpaccessor.HttpContext.GetTokenAsync("access_token").Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",accessToken);
client.DefaultRequestVersion = new Version(2,0);
client.BaseAddress = new Uri(configuration["Api_Location"]);
_httpClient = client;
_logger = logger;
}
我需要在API调用中添加哪些内容以进行验证?