我正在使用ADAL
令牌在Xamarin Forms
项目中调用我的WebAPI。但是ADAL
令牌在1小时后到期,http
次来电将被授权。
我想在收到未经授权的状态时刷新令牌。我阅读了一些示例并说使用DelegatingHandler
,但我不知道DelegatingHandler
是什么以及如何将其与HTTP client
一起使用。
答案 0 :(得分:0)
根据您的描述,我检查了这个问题。要使用DelegatingHandler
,您可以参考以下代码段:
<强> CustomMessageHandler:强>
public class CustomMessageHandler: DelegatingHandler
{
private string _accessToken;
private string _refreshToken;
public CustomMessageHandler(string accessToken, string refreshToken)
{
_accessToken = accessToken;
_refreshToken = refreshToken;
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
var response= await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
/* TODO:
* 1. Retrieve the new access_token via the refresh_token
* 2. Update the current field _accessToken
* 3. Retry the previous failed request
*/
}
return response;
}
}
<强>用法:强>
HttpClient client = new HttpClient(new CustomMessageHandler("{your-access-token}", "{your-refresh-token}"));