I am developing an end point for Client Credential flow (to enable resource server to get access token from the auth server). Can you help me with sample code to generate the access token?
if (request.IsClientCredentialsGrantType())
{
//Code
}
The request to contain the grant_type=client_credentials, client_id="" & client_secret="". Is this suffice?
Something like that should work:
[HttpPost("~/connect/token")]
[Produces("application/json")]
public async Task<IActionResult> Exchange() {
var request = HttpContext.GetOpenIdConnectRequest();
if (request.IsClientCredentialsGrantType()) {
var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);
identity.AddClaim(ClaimTypes.NameIdentifier, request.ClientId,
OpenIdConnectConstants.Destinations.AccessToken);
// Create a new authentication ticket holding the user identity.
var ticket = new AuthenticationTicket(
new ClaimsPrincipal(identity),
new AuthenticationProperties(),
OpenIdConnectServerDefaults.AuthenticationScheme);
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
}
return BadRequest(new OpenIdConnectResponse {
Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
ErrorDescription = "The specified grant type is not supported."
});
}
Thanks a lot! I just added the below mentioned code to validate the client_id and client_secret. This comes above your code. Please correct me if I am wrong here...
var application = await _applicationManager.FindByClientIdAsync(request.ClientId);
if (application == null)
{
//Handle logging and response back to client
}
var validateClient = await _applicationManager.ValidateSecretAsync(application, request.ClientSecret);
if (!validateClient)
{
//Handle logging and response back to client
}
//Code to generate access token
@ksmuthuus note: validating the client credentials in your own code is not necessary as it's always done by OpenIddict as part of the token request validation process.
Most helpful comment
@ksmuthuus note: validating the client credentials in your own code is not necessary as it's always done by OpenIddict as part of the token request validation process.