public async Task When_Passing_Null_Parameters_Then_Exception_Is_Thrown() { // ARRANGE InitializeFakeObjects(); // ACT & ASSERTS await Assert.ThrowsAsync <ArgumentNullException>(() => _clientHelper.GenerateIdTokenAsync(string.Empty, null)); await Assert.ThrowsAsync <ArgumentNullException>(() => _clientHelper.GenerateIdTokenAsync("client_id", null)); }
public async Task <GrantedToken> Execute(RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter) { if (refreshTokenGrantTypeParameter == null) { throw new ArgumentNullException(nameof(refreshTokenGrantTypeParameter)); } // 1. Validate parameters var grantedToken = await ValidateParameter(refreshTokenGrantTypeParameter); // 2. Generate a new access token & insert it var generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync( grantedToken.ClientId, grantedToken.Scope, grantedToken.UserInfoPayLoad, grantedToken.IdTokenPayLoad); generatedToken.ParentTokenId = grantedToken.Id; await _grantedTokenRepository.InsertAsync(generatedToken); // 3. Fill-in the idtoken if (generatedToken.IdTokenPayLoad != null) { generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(generatedToken.ClientId, generatedToken.IdTokenPayLoad); } _simpleIdentityServerEventSource.GrantAccessToClient(generatedToken.ClientId, generatedToken.AccessToken, generatedToken.Scope); return(generatedToken); }
public async Task <GrantedToken> GenerateTokenAsync(Client client, string scope, JwsPayload userInformationPayload = null, JwsPayload idTokenPayload = null) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (string.IsNullOrWhiteSpace(scope)) { throw new ArgumentNullException(nameof(scope)); } var expiresIn = (int)await _configurationService.GetTokenValidityPeriodInSecondsAsync(); // 1. Retrieve the expiration time of the granted token. var jwsPayload = await _jwtGenerator.GenerateAccessToken(client, scope.Split(' ')); // 2. Construct the JWT token (client). var accessToken = await _clientHelper.GenerateIdTokenAsync(client, jwsPayload); var refreshTokenId = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); // 3. Construct the refresh token. return(new GrantedToken { AccessToken = accessToken, RefreshToken = Convert.ToBase64String(refreshTokenId), ExpiresIn = expiresIn, TokenType = Constants.StandardTokenTypes.Bearer, CreateDateTime = DateTime.UtcNow, // IDS Scope = scope, UserInfoPayLoad = userInformationPayload, IdTokenPayLoad = idTokenPayload, ClientId = client.ClientId }); }
/// <summary> /// Generate the JWS payload for identity token. /// If at least one claim is defined then returns the filtered result /// Otherwise returns the default payload based on the scopes. /// </summary> /// <param name="jwsPayload"></param> /// <param name="authorizationParameter"></param> /// <returns></returns> private async Task <string> GenerateIdToken( JwsPayload jwsPayload, AuthorizationParameter authorizationParameter) { return(await _clientHelper.GenerateIdTokenAsync(authorizationParameter.ClientId, jwsPayload)); }
public async Task <GrantedToken> Execute(RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName) { if (refreshTokenGrantTypeParameter == null) { throw new ArgumentNullException(nameof(refreshTokenGrantTypeParameter)); } // 1. Try to authenticate the client var instruction = CreateAuthenticateInstruction(refreshTokenGrantTypeParameter, authenticationHeaderValue, certificate); var authResult = await _authenticateClient.AuthenticateAsync(instruction, issuerName); var client = authResult.Client; if (authResult.Client == null) { _oauthEventSource.Info(authResult.ErrorMessage); throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage); } // 2. Check client if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.refresh_token)) { throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.refresh_token)); } // 3. Validate parameters var grantedToken = await ValidateParameter(refreshTokenGrantTypeParameter); if (grantedToken.ClientId != client.ClientId) { throw new IdentityServerException(ErrorCodes.InvalidGrant, ErrorDescriptions.TheRefreshTokenCanBeUsedOnlyByTheSameIssuer); } // 4. Generate a new access token & insert it var generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync( grantedToken.ClientId, grantedToken.Scope, issuerName, grantedToken.UserInfoPayLoad, grantedToken.IdTokenPayLoad); generatedToken.ParentTokenId = grantedToken.Id; // 5. Fill-in the idtoken if (generatedToken.IdTokenPayLoad != null) { await _jwtGenerator.UpdatePayloadDate(generatedToken.IdTokenPayLoad); generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(generatedToken.ClientId, generatedToken.IdTokenPayLoad); } await _tokenStore.AddToken(generatedToken); _oauthEventSource.GrantAccessToClient(generatedToken.ClientId, generatedToken.AccessToken, generatedToken.Scope); return(generatedToken); }
public async Task <GrantedToken> GenerateTokenAsync(IEnumerable <string> audiences, IEnumerable <TicketLine> ticketLines, string scope, string issuerName) { if (audiences == null) { throw new ArgumentNullException(nameof(audiences)); } if (ticketLines == null) { throw new ArgumentNullException(nameof(ticketLines)); } if (string.IsNullOrWhiteSpace(scope)) { throw new ArgumentNullException(nameof(scope)); } var expiresIn = await _configurationService.GetRptLifeTime().ConfigureAwait(false); // 1. Retrieve the expiration time of the granted token. var jwsPayload = await _jwtGenerator.GenerateAccessToken(audiences, scope.Split(' '), issuerName).ConfigureAwait(false); // 2. Construct the JWT token (client). var jArr = new JArray(); foreach (var ticketLine in ticketLines) { var jObj = new JObject(); jObj.Add(Constants.RptClaims.ResourceSetId, ticketLine.ResourceSetId); jObj.Add(Constants.RptClaims.Scopes, string.Join(" ", ticketLine.Scopes)); jArr.Add(jObj); } jwsPayload.Add(Constants.RptClaims.Ticket, jArr); var clientId = audiences.First(); var accessToken = await _clientHelper.GenerateIdTokenAsync(clientId, jwsPayload).ConfigureAwait(false); var refreshTokenId = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); // 3. Construct the refresh token. return(new GrantedToken { AccessToken = accessToken, RefreshToken = Convert.ToBase64String(refreshTokenId), ExpiresIn = expiresIn, TokenType = SimpleIdServer.Core.Constants.StandardTokenTypes.Bearer, CreateDateTime = DateTime.UtcNow, Scope = scope, ClientId = clientId }); }
public async Task <GrantedToken> Execute( AuthorizationCodeGrantTypeParameter authorizationCodeGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue) { if (authorizationCodeGrantTypeParameter == null) { throw new ArgumentNullException(nameof(authorizationCodeGrantTypeParameter)); } var result = await ValidateParameter( authorizationCodeGrantTypeParameter, authenticationHeaderValue); // Invalidate the authorization code by removing it ! await _authorizationCodeRepository.RemoveAsync(result.Code.Code); var grantedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync( result.Code.Scopes, result.Code.ClientId, result.Code.IdTokenPayload, result.Code.UserInfoPayLoad); if (grantedToken == null) { grantedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync( result.Code.ClientId, result.Code.Scopes, result.Code.UserInfoPayLoad, result.Code.IdTokenPayload); await _grantedTokenRepository.InsertAsync(grantedToken); _simpleIdentityServerEventSource.GrantAccessToClient( result.Code.ClientId, grantedToken.AccessToken, grantedToken.IdToken); } // Fill-in the id-token if (grantedToken.IdTokenPayLoad != null) { grantedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(result.Client, grantedToken.IdTokenPayLoad); } return(grantedToken); }
public async Task <GrantedToken> Execute(AuthorizationCodeGrantTypeParameter authorizationCodeGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName) { if (authorizationCodeGrantTypeParameter == null) { throw new ArgumentNullException(nameof(authorizationCodeGrantTypeParameter)); } var result = await ValidateParameter(authorizationCodeGrantTypeParameter, authenticationHeaderValue, certificate, issuerName).ConfigureAwait(false); await _authorizationCodeStore.RemoveAuthorizationCode(result.AuthCode.Code); // 1. Invalidate the authorization code by removing it ! var grantedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync( result.AuthCode.Scopes, result.AuthCode.ClientId, result.AuthCode.IdTokenPayload, result.AuthCode.UserInfoPayLoad).ConfigureAwait(false); if (grantedToken == null) { grantedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(result.Client, result.AuthCode.Scopes, issuerName, result.AuthCode.UserInfoPayLoad, result.AuthCode.IdTokenPayload).ConfigureAwait(false); _oauthEventSource.GrantAccessToClient( result.AuthCode.ClientId, grantedToken.AccessToken, grantedToken.IdToken); // Fill-in the id-token if (grantedToken.IdTokenPayLoad != null) { await _jwtGenerator.UpdatePayloadDate(grantedToken.IdTokenPayLoad).ConfigureAwait(false); grantedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(result.Client, grantedToken.IdTokenPayLoad).ConfigureAwait(false); } await _tokenStore.AddToken(grantedToken).ConfigureAwait(false); } return(grantedToken); }
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); }
public async Task <GrantedToken> Execute(ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName) { 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, issuerName); var client = authResult.Client; if (authResult.Client == null) { _oauthEventSource.Info(authResult.ErrorMessage); throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage); } // 2. Check the client. if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.password)) { throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.password)); } if (client.ResponseTypes == null || !client.ResponseTypes.Contains(ResponseType.token) || !client.ResponseTypes.Contains(ResponseType.id_token)) { throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheResponseType, client.ClientId, "token id_token")); } // 3. Try to authenticate a resource owner var resourceOwner = await _resourceOwnerAuthenticateHelper.Authenticate(resourceOwnerGrantTypeParameter.UserName, resourceOwnerGrantTypeParameter.Password, resourceOwnerGrantTypeParameter.AmrValues); if (resourceOwner == null) { throw new IdentityServerException(ErrorCodes.InvalidGrant, ErrorDescriptions.ResourceOwnerCredentialsAreNotValid); } // 4. 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); } // 5. 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.GenerateIdTokenPayloadForScopesAsync(claimsPrincipal, authorizationParameter, issuerName); var generatedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId, payload, payload); if (generatedToken == null) { generatedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client, allowedTokenScopes, issuerName, payload, payload); if (generatedToken.IdTokenPayLoad != null) { await _jwtGenerator.UpdatePayloadDate(generatedToken.IdTokenPayLoad); generatedToken.IdToken = await _clientHelper.GenerateIdTokenAsync(client, generatedToken.IdTokenPayLoad); } await _tokenStore.AddToken(generatedToken); _oauthEventSource.GrantAccessToClient(client.ClientId, generatedToken.AccessToken, allowedTokenScopes); } return(generatedToken); }