public async Task <GrantedToken> Execute(ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate = null) { if (resourceOwnerGrantTypeParameter == null) { throw new ArgumentNullException(nameof(resourceOwnerGrantTypeParameter)); } // 1. Try to authenticate the client var instruction = CreateAuthenticateInstruction(resourceOwnerGrantTypeParameter, authenticationHeaderValue, certificate); var authResult = await _authenticateClient.AuthenticateAsync(instruction); var client = authResult.Client; if (authResult.Client == null) { _simpleIdentityServerEventSource.Info(ErrorDescriptions.TheClientCannotBeAuthenticated); client = await _clientRepository.GetClientByIdAsync(Constants.AnonymousClientId); if (client == null) { throw new IdentityServerException(ErrorCodes.InternalError, string.Format(ErrorDescriptions.ClientIsNotValid, Constants.AnonymousClientId)); } } // 2. Try to authenticate a resource owner var resourceOwner = await _authenticateResourceOwnerService.AuthenticateResourceOwnerAsync(resourceOwnerGrantTypeParameter.UserName, resourceOwnerGrantTypeParameter.Password); if (resourceOwner == null) { throw new IdentityServerException(ErrorCodes.InvalidGrant, ErrorDescriptions.ResourceOwnerCredentialsAreNotValid); } // 3. Check if the requested scopes are valid var allowedTokenScopes = string.Empty; if (!string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope)) { var scopeValidation = _scopeValidator.Check(resourceOwnerGrantTypeParameter.Scope, client); if (!scopeValidation.IsValid) { throw new IdentityServerException(ErrorCodes.InvalidScope, scopeValidation.ErrorMessage); } allowedTokenScopes = string.Join(" ", scopeValidation.Scopes); } // 4. Generate the user information payload and store it. var claims = resourceOwner.Claims; var claimsIdentity = new ClaimsIdentity(claims, "simpleIdentityServer"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authorizationParameter = new AuthorizationParameter { Scope = resourceOwnerGrantTypeParameter.Scope }; var payload = await _jwtGenerator.GenerateUserInfoPayloadForScopeAsync(claimsPrincipal, authorizationParameter); var generatedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId, payload, payload); if (generatedToken == null) { generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client.ClientId, allowedTokenScopes, payload, payload); await _grantedTokenRepository.InsertAsync(generatedToken); // Fill-in the id-token if (generatedToken.IdTokenPayLoad != null) { generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(client, generatedToken.IdTokenPayLoad); } _simpleIdentityServerEventSource.GrantAccessToClient(client.ClientId, generatedToken.AccessToken, allowedTokenScopes); } return(generatedToken); }