我有一个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");
});
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",
IdentityServerConstants.LocalApi.ScopeName
},
AllowedCorsOrigins = { "https://localhost:44370" },
AlwaysSendClientClaims = true,
AlwaysIncludeUserClaimsInIdToken = true,
AllowOfflineAccess = true,
AccessTokenLifetime = 1,//testing
UpdateAccessTokenClaimsOnRefresh = true
},
...
是,您还应该获取刷新令牌,以继续获取新的访问令牌。要从IdentityServer获取刷新令牌,您需要在客户端的“ AllowedScopes”属性中添加“ offline_access”范围。您还需要将客户端上的'AllowOfflineAccess'属性设置为true。
此后,您需要在客户端发送的范围中包括'offline_access',并且您应该在响应中收到刷新令牌。
要使用刷新令牌,请将您发送给代码交换的所有内容发送到令牌端点的请求,除了将'code'参数替换为'refresh_token',并将'grant_type'的值从'code'更改为'refresh_token' 。 IdentityServer4对此请求的响应应包含一个id_token,一个access_token和一个新的refresh_token。