Created
July 11, 2017 20:42
-
-
Save barchito/5a75be49531fbeccbd9364c96aef1582 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Retrieve token for the user | |
/// </summary> | |
/// <param name="request"></param> | |
/// <returns></returns> | |
[HttpPost("~/connect/token"), Consumes("application/x-www-form-urlencoded"), Produces("application/json")] | |
[ProducesResponseType(typeof(ErrorResponse), 400)] | |
[ProducesResponseType(typeof(Microsoft.AspNetCore.Mvc.SignInResult), 200)] | |
[AllowAnonymous] | |
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.IsPasswordGrantType()) | |
{ | |
var user = await _userManager.FindByNameAsync(request.Username); | |
if (user == null) | |
{ | |
return BadRequest(ErrorResponse.FromErrorString("The username/password couple is invalid.")); | |
} | |
// Ensure the user is allowed to sign in. | |
if (!await _signInManager.CanSignInAsync(user)) | |
{ | |
return BadRequest(ErrorResponse.FromErrorString("The specified user is not allowed to sign in.")); | |
} | |
// Reject the token request if two-factor authentication has been enabled by the user. | |
//if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user)) | |
//{ | |
// return BadRequest(ErrorResponse.FromErrorString("The specified user is not allowed to sign in.")); | |
//} | |
// Ensure the user is not already locked out. | |
if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user)) | |
{ | |
return BadRequest(ErrorResponse.FromErrorString("The username/password couple is invalid.")); | |
} | |
// Ensure the password is valid. | |
if (!await _userManager.CheckPasswordAsync(user, request.Password)) | |
{ | |
if (_userManager.SupportsUserLockout) | |
{ | |
await _userManager.AccessFailedAsync(user); | |
} | |
return BadRequest(ErrorResponse.FromErrorString("The username/password couple is invalid.")); | |
} | |
if (_userManager.SupportsUserLockout) | |
{ | |
await _userManager.ResetAccessFailedCountAsync(user); | |
} | |
// Create a new authentication ticket. | |
var ticket = await CreateTicketAsync(request, user); | |
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme); | |
} | |
return BadRequest(ErrorResponse.FromErrorString("The specified grant type is not supported.")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment