以下代码引发错误:
An unhandled exception occurred while processing the request.
ArgumentException: Parameter is required
Parameter name: refresh_token
我想检查我的令牌是否在特定的时间阈值内过期,如果可以的话可以自动更新。代码如下:-
public async Task<HttpClient> GetClient()
{
string token = string.Empty;
var currentContext = _contextAccessor.HttpContext;
var _client = _factory.CreateClient();
var expiresAt = await currentContext.GetTokenAsync("expires_at");
if (string.IsNullOrWhiteSpace(expiresAt) || ((DateTime.Parse(expiresAt).AddSeconds(-60)).ToUniversalTime() < DateTime.UtcNow))
{
token = await RenewToken();
}
else
{
token = await currentContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
}
if (!string.IsNullOrWhiteSpace(token))
{
_client.SetBearerToken(token);
}
_client.BaseAddress = new Uri(Contants.APIServices);
_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
_client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
_client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "AnalyzerStatusCheck");
return _client;
}
在此代码块上引发异常(var tokenResult = await tokenClient.RequestRefreshTokenAsync(new RefreshTokenRequest)
private async Task<string> RenewToken()
{
var currentContext = _contextAccessor.HttpContext;
var response = await _cache.GetAsync();
if (response.IsError) throw new Exception(response.Error);
var refreshToken = await currentContext.GetTokenAsync("refresh_token");
var tokenClient = _factory.CreateClient();
var tokenResult = await tokenClient.RequestRefreshTokenAsync(new RefreshTokenRequest
{
Address = response.TokenEndpoint,
ClientId = "ktswebclient",
ClientSecret = "secret",
RefreshToken = refreshToken
});
if (!tokenResult.IsError)
{
var oldToken = await currentContext.GetTokenAsync("id_token");
var newAccessToken = tokenResult.AccessToken;
var newRefreshToken = tokenResult.RefreshToken;
var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);
var info = await currentContext.AuthenticateAsync("Cookies");
info.Properties.UpdateTokenValue("refresh_token", newRefreshToken);
info.Properties.UpdateTokenValue("access_token", newAccessToken);
info.Properties.UpdateTokenValue("expires_at", expiresAt.ToString("o", CultureInfo.InvariantCulture));
await currentContext.SignInAsync("Cookies", info.Principal, info.Properties);
return tokenResult.AccessToken;
}
else
{
throw new Exception("Problem encountered while refreshing tokens.",
tokenResult.Exception);
}
}
IDP代码:-
public static IEnumerable<Client> GetClients()
{
return new List<Client>()
{
new Client
{
ClientName="KtsWeb App",
ClientId="ktswebclient",
AllowedGrantTypes= GrantTypes.Hybrid,
AccessTokenType = AccessTokenType.Reference,
AccessTokenLifetime = 120,
AllowOfflineAccess = true,
UpdateAccessTokenClaimsOnRefresh = true,
RefreshTokenUsage = TokenUsage.ReUse,
RedirectUris = new List<string>()
{
"https://localhost:44355/signin-oidc" //Client URL Address
},
PostLogoutRedirectUris = new List<string>()
{
"https://localhost:44355/signout-callback-oidc"
},
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Address,
"roles",
"ktswebapi",
"country",
"subscriptionlevel"
},
ClientSecrets =
{
new Secret("secret".Sha256())
}
// AlwaysIncludeUserClaimsInIdToken = true
}
};
}