【问题标题】:Correctly handle HttpStatusCode=Unauthorized with ADAL token使用 ADAL 令牌正确处理 HttpStatusCode=Unauthorized
【发布时间】:2018-02-23 20:46:28
【问题描述】:

我正在使用ADAL 令牌在Xamarin Forms 项目中调用我的WebAPI。但是ADAL 令牌会在 1 小时后过期,http 调用会抛出未经授权。

我想在收到未授权状态时刷新令牌。我读过一些例子说要使用 DelegatingHandler ,但我不知道 DelegatingHandler 是什么以及如何将它与 HTTP client 一起使用。

【问题讨论】:

  • 当你收到一个token时,后面跟着一个过期时间,每次发出请求时检查token是否即将过期,并使用刷新token请求一个新的

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


【解决方案1】:

根据您的描述,我检查了这个问题。使用DelegatingHandler可以参考以下代码sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 2016-05-03
    • 2017-12-10
    • 2018-04-14
    • 2019-06-15
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多