httpclient令牌对此请求的授权已被拒绝

时间:2019-03-11 14:17:19

标签: c# httpclient

我使用基于令牌的身份验证创建的MVC网站上有一个API。这在我的一个应用程序上效果很好,但在另一个应用程序上却显示“此请求的授权已被拒绝。”。

我获得的令牌还不错,但是打电话时我遇到了以上错误。

这是我创建的测试。

class TestApi
{
    private const string baseAddress = "http://localhost:50485";

    private const string baseApiAddress = baseAddress + "/api/DojoDbApi";
    async Task<string> GetToken(string userName, string password)
    {
        var keyValues = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("username", userName),
            new KeyValuePair<string, string>("password", password),
            new KeyValuePair<string, string>("grant_type", "password")
        };
        var request = new HttpRequestMessage(HttpMethod.Post, "/oauth/token") { Content = new FormUrlEncodedContent(keyValues) };
        var client = new HttpClient { MaxResponseContentBufferSize = 256000, BaseAddress = new Uri(baseAddress) };

        var response = await client.SendAsync(request).ConfigureAwait(false);
        var content = await response.Content.ReadAsStringAsync();
        JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
        var accessToken = jwtDynamic.Value<string>("access_token");
        Debug.WriteLine(accessToken);

        return accessToken;
    }
    public async Task<string> GetHello(string userName, string password)
    {


        var accessToken = await GetToken(userName, password);
        var client = new HttpClient { MaxResponseContentBufferSize = 256000, BaseAddress = new Uri(baseApiAddress) };
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // Add the Authorization header with the AccessToken.
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            var response = await client.GetAsync(new Uri(baseApiAddress + "/Hello"));
            var s = await response.Content.ReadAsStringAsync();
            Debug.WriteLine(s);
            return s;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(@"              ERROR {0}", ex.Message);
            return ex.Message;
        }
    }

}

真正令我困惑的是,我可以使用Delphi应用程序愉快地访问API。

1 个答案:

答案 0 :(得分:0)

已经与其他开发人员(在ChesterDevs聚会中)进行了讨论。

这与Cookie有关。

如果您附加?AspxAutoDetectCookieSupport = 1,则调用会起作用。

如果您将Web配置中的无cookie更改为“ UseCookies”,则它将正常工作。

How to remove AspxAutoDetectCookieSupport=1

相关问题