【发布时间】:2018-10-21 21:07:26
【问题描述】:
我正在从 .NET Core 1.1 迁移到 2.0,现在我也必须更新我的身份验证。
我将 OAuth 和 OpenIddict 用于 .NET Core 2.0
当我将请求发送到我的 connect/token 时,我得到了这个:
OpenIddict.Server.OpenIddictServerHandler[0] 令牌响应是 成功返回:{
“错误”:“unsupported_grant_type”,
"error_description": "指定的'grant_type'参数不是 支持。”
}。
这是我的请求方法:
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, $"{url}/connect/token");
request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = clientId,
["client_secret"] = clientSecret,
["pessoaid"] = pessoaId,
["usuarioid"] = usuarioId,
["conta"] = conta,
["cpfcnpj"] = userDoubleCpf,
["fonteDados"] = fonteDados,
["userIdsLogged"] = userIdsLogged
});
var response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
response.EnsureSuccessStatusCode();
var result = JObject.Parse(await response.Content.ReadAsStringAsync());
if (result["error"] != null)
{
throw new InvalidOperationException("An error occurred while retrieving an access token.");
}
return result;
}
当应用程序链接到用户帐户时会生成我的 OpenIddictApplications,因此当登录请求发送到我的 API 并检索相应的值时会生成 ClientId 和 Secret。
我遵循了 oppeniddict documentation 并将所有内容都包含在我的 Startup.cs 中
这是我的授权控制器:
[HttpPost("~/connect/token"), Produces("application/json")]
public async Task<IActionResult> Exchange(OpenIdConnectRequest request)
{
Debug.Assert(request.IsTokenRequest(),
"The OpenIddict binder for ASP.NET Core MVC is not registered. " +
"Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");
if (request.IsClientCredentialsGrantType())
{
// Note: the client credentials are automatically validated by OpenIddict:
// if client_id or client_secret are invalid, this action won't be invoked.
var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);
if (application == null)
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidClient,
ErrorDescription = "The client application was not found in the database."
});
}
// Create a new authentication ticket.
var ticket = CreateTicket(request, application);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
我正在生成 AuthenticationTicket 并返回它。
当我尝试发送获取我的令牌的请求时,知道什么可能导致这种错误请求吗?
【问题讨论】:
标签: c# oauth-2.0 openiddict