如何使用refresh_token从Xamarin.Forms客户端中的身份服务器获取新的访问 token ?
我按照教程https://sinclairinat0r.com/2018/12/09/secure-data-access-with-identityserver4-and-xamarin-forms进行操作并创建了 Xamarin Forms 移动应用程序,并在 IS4 上进行了身份验证。我将访问 token 的生命周期设置为几分钟。访问 token 过期后(如异常(exception)),应用程序将无法再访问授权端点。我有一个刷新 token ,但我不知道如何使用它从身份服务器获取新的访问 token 。
is4 配置中指定的客户端:
new Client()
{
ClientId = "xamarin-client",
ClientName = "Xamarin client",
AllowedGrantTypes = { "authorization_code" },
AllowedScopes = {"openid", "profile", "values-api" },
AllowAccessTokensViaBrowser = true,
AllowOfflineAccess = true,
AlwaysIncludeUserClaimsInIdToken = true,
RequirePkce = true,
RequireClientSecret = false,
RedirectUris = { "https://iglooidentityserver.azurewebsites.net/grants" },
AccessTokenLifetime = 180,
}
我使用过的身份验证器:
var oAuth = new OAuth2AuthenticatorEx(
"xamarin-client",
"offline_access values-api",
new Uri("https://iglooidentityserver.azurewebsites.net/connect/authorize"),
new Uri("https://iglooidentityserver.azurewebsites.net/grants"))
{
AccessTokenUrl = new Uri("https://iglooidentityserver.azurewebsites.net/connect/token"),
ShouldEncounterOnPageLoading = false,
};
var presenter = new OAuthLoginPresenter();
presenter.Completed += Presenter_Completed;
presenter.Login(oAuth);
最佳答案
我在一个旧项目中处理了这个问题,如下,希望这对你有帮助。
public async Task<string> GetAccessToken()
{
if ((_authService.AuthAccessTokenExpireIn - DateTime.Now).TotalMinutes < 10) {
var authResponse = await GetRefreshTokenAsync(_authService.AuthRefreshToken);
_authService.AuthAccessToken = authResponse.AccessToken;
_authService.AuthRefreshToken = authResponse.RefreshToken;
_authService.AuthAccessTokenExpireIn = authResponse.ExpiresIn;
}
return _authService.AuthAccessToken;
}
public async Task<UserToken> GetRefreshTokenAsync(string currentRefreshToken)
{
string data = string.Format("grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", GlobalSetting.Instance.ClientId, GlobalSetting.Instance.ClientSecret, refreshToken);
var token = await PostAsync<UserToken>(_httpClient,
GlobalSetting.Instance.TokenEndpoint,
data);
return token;
}
public async Task<UserToken> PostAsync<UserToken>(HttpClient httpClient, string uri, object data)
{
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(uri, content);
await HandleResponse(response);
string serialized = await response.Content.ReadAsStringAsync();
UserToken result = await Task.Run(() => JsonConvert.DeserializeObject<UserToken>(serialized, _serializerSettings));
return result;
}
关于xamarin.forms - 如何使用刷新 token 通过 Xamarin.Forms 客户端从身份服务器 4 获取新的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079375/