這工作得很好,但我想知道什麼是最乾淨的方式來支持我想要實現的。
我會親自去與一個自定義的補助類型:
[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訪問令牌的示例:
實施令牌驗證例程時,因爲這一步是特別容易出錯要極其小心。驗證所有內容非常重要,包括觀衆(否則,your server would be vulnerable to confused deputy attacks)。
這是完美的!非常感謝。 –