使用ADAL令牌正确处理HttpStatusCode = Unauthorized

时间:2017-09-14 18:51:15

标签: c# asp.net azure xamarin.forms

我正在使用ADAL令牌在Xamarin Forms项目中调用我的WebAPI。但是ADAL令牌在1小时后到期,http次来电将被授权。

我想在收到未经授权的状态时刷新令牌。我阅读了一些示例并说使用DelegatingHandler,但我不知道DelegatingHandler是什么以及如何将其与HTTP client一起使用。

1 个答案:

答案 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}"));