HttpClient System.Net.Http.HttpRequestException: 响应状态码不表示成功: 401 (Unauthorized)

HttpClient System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized)

我正在尝试从我的 asp.net 核心应用程序向 Auth0 发送请求。 为此,我正在使用 HttpClient

问题是,当我在邮递员中创建相同的请求时,一切正常,但如果我从我的 .NET Core 应用程序中使用它,它就会抛出

System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).

这是邮递员示例的图片:

有关任务的更多详细信息:

请求类型是POST

调用成功会returnaccess_token

POST 请求需要很少的正文参数:

  1. grant_type
  2. client_id
  3. client_secret
  4. 听众

Header 内容类型必须是 application/x-www-form-urlencoded.

所以邮递员的请求是这样的:

https://mydemoapplication.auth0.com/oauth/token? grant_type=client_credentials &client_id=some_my_id &client_secret=some_my_client_secrets &audience=https://mydemoapplication.auth0.com/api/v2/

而且这工作得很好。

但是当我尝试从 .NET CORE Web api 重复相同的操作时,我总是得到 401 (Unauthorized).

这是我的 C# 代码:

首先我们从方法开始 RequestTokenFromAuth0

 public async Task<string> RequestTokenFromAuth0(CancellationToken cancellationToken)
 {
            // tokenUrl represents https://mydemoapplication.auth0.com/oauth/token
            var tokenUrl = $"{_auth0HttpConfig.TokenEndpoint}";

            // Creating anonymous object which will be used in post request
            var data = new
            {
                grant_type = "client_credentials",
                client_id =  _auth0HttpConfig.ClientId ,
                client_secret = _auth0HttpConfig.ClientSecret,
                audience = _auth0HttpConfig.Audience
            };

            //var data = $"grant_type=client_credentials&client_id={_auth0HttpConfig.ClientId}&client_secret={_auth0HttpConfig.ClientSecret}&audience={_auth0HttpConfig.Audience}";

            var response = await _auth0Client.PostToken<Auth0Auth>(tokenUrl, data, cancellationToken);
             
            if(response!= null && response.Success && response.Data != null && !string.IsNullOrWhiteSpace(response.Data.Token))
            {
                return response.Data.Token;
            }
            else
            {
                throw new ArgumentException("Token is not retrieved.");
            }
        }


public async Task<T> PostToken<T>(string endpoint, object jsonObject, CancellationToken cancellationToken)
{
    if (string.IsNullOrWhiteSpace(endpoint))
    {
        throw new ArgumentNullException(endpoint);
    }

    var reqMessage = GenerateTokenRequestMessage(HttpMethod.Post, jsonObject, endpoint);

    var result = await GetResult<T>(httpRequestMessage, cancellationToken);

    return result;
}


public HttpRequestMessage GenerateTokenRequestMessage(HttpMethod httpMethod, object objectToPost, string endpoint)
{ 
    var httpRequestMessage = new HttpRequestMessage(httpMethod, endpoint);

    var serializedObjectToCreate = JsonConvert.SerializeObject(objectToPost, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

    httpRequestMessage.Content = new StringContent(serializedObjectToCreate);
    httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    return httpRequestMessage;
}

private async Task<T> GetResult<T>(HttpRequestMessage request, CancellationToken cancellationToken)
{
    try
    {
        HttpResponseMessage response = await _client.SendAsync(request, cancellationToken);

        response.EnsureSuccessStatusCode(); // THIS LINE Throws exception 401 Unathorized

        var result = await response.Content.ReadAsStringAsync();

        return JsonConvert.DeserializeObject<T>(result);
    }
    catch (Exception ex)
    {
        throw;
    }
}

这里出了点问题,我不知道为什么我不被认可,这里可能出了什么问题我真的不确定!任何形式的帮助都会很棒!

P.S 邮递员再次重复一切正常!

谢谢

干杯

由于您是从 dotnet 访问它,我建议使用 Auth0 NuGet 包。

  1. 安装包Auth0.AuthenticationApi
  2. 使用此基本代码作为您获取令牌的真实代码的大纲
public class QuestionCode
{
    public async Task<string> GetToken()
    {
        var client = new AuthenticationApiClient("<your_auth0_domain>");
        var tokenRequest = new ClientCredentialsTokenRequest
        {
            ClientId = "<your_client_id>",
            ClientSecret = "<your_client_secret>",
            Audience = "<your_audience>",
        };

        var token = await client.GetTokenAsync(tokenRequest);
        return token.AccessToken;
    }
}

我针对虚拟 Auth0 API 测试了它,它按预期工作。

编码愉快!

_auth0Client.PostToken<Auth0Auth>(tokenUrl, data, cancellationToken);

并且 PostTokendata 作为 object jsonObject 并将其传递给 GenerateTokenRequestMessage 然后创建 HTTP 内容:

var serializedObjectToCreate = JsonConvert.SerializeObject(objectToPost, new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore
});

httpRequestMessage.Content = new StringContent(serializedObjectToCreate);
httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

但是在这里您输入序列化为 JSON 的数据并期望它是 application/x-www-form-urlencoded。但事实显然并非如此。您生成的内容如下所示:

{"grant_type":"client_credentials","client_id":"ClientId","client_secret":"ClientSecret","audience":"Audience"}

但是,它应该是这样的:

grant_type=client_credentials&client_id=ClientId&client_secret=ClientSecret&audience=Audience

您可以为此使用 FormUrlEncodedContent 类型:

httpRequestMessage.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
    ["grant_type"] = "client_credentials",
    ["client_id"] = _auth0HttpConfig.ClientId,
    ["client_secret"] = _auth0HttpConfig.ClientSecret,
    ["audience"] = _auth0HttpConfig.Audience,
});