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

问题描述 投票:0回答:1

我在使用基于令牌的身份验证创建的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。

c# httpclient
1个回答
0
投票

一直在与其他开发者讨论这个问题(在ChesterDevs聚会中)。

这与cookie有关。

如果你附加?AspxAutoDetectCookieSupport = 1你可以调用它。

如果您将web config中的cookieless更改为“UseCookies”,那么它将正常工作。

How to remove AspxAutoDetectCookieSupport=1

© www.soinside.com 2019 - 2024. All rights reserved.