这很好用,但我想知道支持我想要实现的目标的最干净的方法是什么。
我个人会使用自定义授权类型:
[HttpPost("~/connect/token")]
[Produces("application/json")]
public IActionResult Exchange(OpenIdConnectRequest request)
{
if (request.GrantType == "urn:ietf:params:oauth:grant-type:google_identity_token")
{
// Reject the request if the "assertion" parameter is missing.
if (string.IsNullOrEmpty(request.Assertion))
{
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.InvalidRequest,
ErrorDescription = "The mandatory 'assertion' parameter was missing."
});
}
// Create a new ClaimsIdentity containing the claims that
// will be used to create an id_token and/or an access token.
var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
// Manually validate the identity token issued by Google,
// including the issuer, the signature and the audience.
// Then, copy the claims you need to the "identity" instance.
// Create a new authentication ticket holding the user identity.
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
OpenIdConnectServerDefaults.AuthenticationScheme);
ticket.SetScopes(
OpenIdConnectConstants.Scopes.OpenId,
OpenIdConnectConstants.Scopes.OfflineAccess);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse
{
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
请注意,您还必须在 OpenIddict 选项中启用它:
// Register the OpenIddict services.
services.AddOpenIddict()
// Register the Entity Framework stores.
.AddEntityFrameworkCoreStores<ApplicationDbContext>()
// Register the ASP.NET Core MVC binder used by OpenIddict.
// Note: if you don't call this method, you won't be able to
// bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
.AddMvcBinders()
// Enable the token endpoint.
.EnableTokenEndpoint("/connect/token")
// Enable the refresh token flow and a custom grant type.
.AllowRefreshTokenFlow()
.AllowCustomFlow("urn:ietf:params:oauth:grant-type:google_identity_token")
// During development, you can disable the HTTPS requirement.
.DisableHttpsRequirement();
发送令牌请求时,请确保使用权限grant_type
并将您的 id_token 作为assertion
参数发送,它应该可以工作。
以下是使用 Facebook 访问令牌的示例:
在实施令牌验证例程时要格外小心,因为这一步特别容易出错。验证所有内容非常重要,包括观众(否则,您的服务器将容易受到混淆代理攻击)。