我正在尝试从我的asp.net核心应用程序向Auth0
发送请求。
我为此使用HttpClient
。
问题是,当我在邮递员中创建相同的请求时,一切正常,但是如果我从我的.NET Core应用程序使用它,则抛出的异常
System.Net.Http.HttpRequestException:响应状态代码不正确 表示成功:401(未授权)。
这是邮递员示例的图像:
请求类型为POST
成功呼叫将返回access_token
POST请求期望的身体参数很少:
和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从邮递员再重复一次,一切正常!
谢谢
欢呼
答案 0 :(得分:2)
_auth0Client.PostToken<Auth0Auth>(tokenUrl, data, cancellationToken);
然后PostToken
将data
作为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,
});
答案 1 :(得分:0)
由于您是从dotnet上访问的,因此建议您使用Auth0 NuGet软件包。
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对此进行了测试,并按预期工作。
快乐编码!