public async Task When_Requesting_Token_Via_AuthorizationCode_Grant_Type_Then_Events_Are_Logged() { // ARRANGE InitializeFakeObjects(); const string clientId = "clientId"; const string code = "code"; const string accessToken = "accessToken"; const string identityToken = "identityToken"; var parameter = new AuthorizationCodeGrantTypeParameter { ClientId = clientId, Code = code }; var grantedToken = new GrantedToken { AccessToken = accessToken, IdToken = identityToken }; _getTokenByAuthorizationCodeGrantTypeActionFake.Setup( g => g.Execute(It.IsAny <AuthorizationCodeGrantTypeParameter>(), It.IsAny <AuthenticationHeaderValue>())) .Returns(Task.FromResult(grantedToken)); // ACT await _tokenActions.GetTokenByAuthorizationCodeGrantType(parameter, null); // ASSERTS _simpleIdentityServerEventSourceFake.Verify(s => s.StartGetTokenByAuthorizationCode(clientId, code)); _simpleIdentityServerEventSourceFake.Verify(s => s.EndGetTokenByAuthorizationCode(accessToken, identityToken)); }
public async Task When_Requesting_Token_Via_Resource_Owner_Credentials_Grant_Type_Then_Events_Are_Logged() { // ARRANGE InitializeFakeObjects(); const string clientId = "clientId"; const string userName = "******"; const string password = "******"; const string accessToken = "accessToken"; const string identityToken = "identityToken"; var parameter = new ResourceOwnerGrantTypeParameter { ClientId = clientId, UserName = userName, Password = password }; var grantedToken = new GrantedToken { AccessToken = accessToken, IdToken = identityToken }; _getTokenByResourceOwnerCredentialsGrantTypeActionFake.Setup( g => g.Execute(It.IsAny <ResourceOwnerGrantTypeParameter>(), It.IsAny <AuthenticationHeaderValue>(), It.IsAny <X509Certificate2>())) .Returns(Task.FromResult(grantedToken)); // ACT await _tokenActions.GetTokenByResourceOwnerCredentialsGrantType(parameter, null); // ASSERTS _simpleIdentityServerEventSourceFake.Verify(s => s.StartGetTokenByResourceOwnerCredentials(clientId, userName, password)); _simpleIdentityServerEventSourceFake.Verify(s => s.EndGetTokenByResourceOwnerCredentials(accessToken, identityToken)); }
public async Task When_Getting_Token_Via_ClientCredentials_GrantType_Then_GrantedToken_Is_Returned() { // ARRANGE InitializeFakeObjects(); const string scope = "valid_scope"; const string clientId = "valid_client_id"; var parameter = new ClientCredentialsGrantTypeParameter { Scope = scope }; var grantedToken = new GrantedToken { ClientId = clientId }; _getTokenByClientCredentialsGrantTypeActionStub.Setup(g => g.Execute(It.IsAny <ClientCredentialsGrantTypeParameter>(), It.IsAny <AuthenticationHeaderValue>())) .Returns(Task.FromResult(grantedToken)); // ACT var result = await _tokenActions.GetTokenByClientCredentialsGrantType(parameter, null); // ASSERTS _simpleIdentityServerEventSourceFake.Verify(s => s.StartGetTokenByClientCredentials(scope)); _simpleIdentityServerEventSourceFake.Verify(s => s.EndGetTokenByClientCredentials(clientId, scope)); Assert.NotNull(result); Assert.True(result.ClientId == clientId); }
public async Task When_Passing_Request_To_Refresh_Token_Grant_Type_Then_Events_Are_Logged() { // ARRANGE InitializeFakeObjects(); const string refreshToken = "refresh_token"; const string accessToken = "accessToken"; const string identityToken = "identityToken"; var parameter = new RefreshTokenGrantTypeParameter { RefreshToken = refreshToken }; var grantedToken = new GrantedToken { AccessToken = accessToken, IdToken = identityToken }; _getTokenByRefreshTokenGrantTypeActionFake.Setup( g => g.Execute(It.IsAny <RefreshTokenGrantTypeParameter>())) .Returns(Task.FromResult(grantedToken)); // ACT await _tokenActions.GetTokenByRefreshTokenGrantType(parameter); // ASSERTS _simpleIdentityServerEventSourceFake.Verify(s => s.StartGetTokenByRefreshToken(refreshToken)); _simpleIdentityServerEventSourceFake.Verify(s => s.EndGetTokenByRefreshToken(accessToken, identityToken)); }
public async Task When_Generating_AuthorizationResponse_With_AccessToken_And_ThereIs_No_Granted_Token_Then_Token_Is_Generated_And_Added_To_The_Parameters() { // ARRANGE InitializeFakeObjects(); const string idToken = "idToken"; const string clientId = "clientId"; const string scope = "openid"; var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity("fake")); var authorizationParameter = new AuthorizationParameter { ClientId = clientId, Scope = scope }; var grantedToken = new GrantedToken { AccessToken = Guid.NewGuid().ToString() }; var actionResult = new ActionResult { RedirectInstruction = new RedirectInstruction() }; var jwsPayload = new JwsPayload(); _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>())) .Returns(new List <ResponseType> { ResponseType.token }); _jwtGeneratorFake.Setup( j => j.GenerateIdTokenPayloadForScopesAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthorizationParameter>())) .Returns(Task.FromResult(jwsPayload)); _jwtGeneratorFake.Setup( j => j.GenerateUserInfoPayloadForScopeAsync(It.IsAny <ClaimsPrincipal>(), It.IsAny <AuthorizationParameter>())) .Returns(Task.FromResult(jwsPayload)); _jwtGeneratorFake.Setup(j => j.EncryptAsync(It.IsAny <string>(), It.IsAny <JweAlg>(), It.IsAny <JweEnc>())) .Returns(Task.FromResult(idToken)); _parameterParserHelperFake.Setup(p => p.ParseScopes(It.IsAny <string>())) .Returns(() => new List <string> { scope }); _grantedTokenHelperStub.Setup(r => r.GetValidGrantedTokenAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <JwsPayload>(), It.IsAny <JwsPayload>())) .Returns(Task.FromResult((GrantedToken)null)); _grantedTokenGeneratorHelperFake.Setup(r => r.GenerateTokenAsync(It.IsAny <Client>(), It.IsAny <string>(), It.IsAny <JwsPayload>(), It.IsAny <JwsPayload>())) .Returns(Task.FromResult(grantedToken)); // ACT await _generateAuthorizationResponse.ExecuteAsync(actionResult, authorizationParameter, claimsPrincipal, new Client()); // ASSERTS Assert.True(actionResult.RedirectInstruction.Parameters.Any(p => p.Name == Core.Constants.StandardAuthorizationResponseNames.AccessTokenName)); Assert.True(actionResult.RedirectInstruction.Parameters.Any(p => p.Value == grantedToken.AccessToken)); _grantedTokenRepositoryFake.Verify(g => g.AddToken(grantedToken)); _simpleIdentityServerEventSource.Verify(e => e.GrantAccessToClient(clientId, grantedToken.AccessToken, scope)); }
public async Task When_Invalidating_Access_Token_Then_GrantedToken_Is_Removed() { // ARRANGE InitializeFakeObjects(); var grantedToken = new GrantedToken { AccessToken = "access_token" }; var parameter = new RevokeTokenParameter { Token = "access_token" }; _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(new AuthenticateInstruction()); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>())) .Returns(() => Task.FromResult(new AuthenticationResult(new Models.Client(), null))); _grantedTokenRepositoryStub.Setup(g => g.GetTokenAsync(It.IsAny <string>())) .Returns(Task.FromResult(grantedToken)); _grantedTokenRepositoryStub.Setup(g => g.GetTokenByRefreshTokenAsync(It.IsAny <string>())) .Returns(() => Task.FromResult((GrantedToken)null)); _grantedTokenRepositoryStub.Setup(g => g.DeleteAsync(It.IsAny <GrantedToken>())) .Returns(Task.FromResult(true)); // ACT await _revokeTokenAction.Execute(parameter, null); // ASSERTS _grantedTokenRepositoryStub.Verify(g => g.DeleteAsync(grantedToken)); }
public async Task When_Invalidating_Refresh_Token_Then_GrantedTokenChildren_Are_Removed() { // ARRANGE InitializeFakeObjects(); var parent = new GrantedToken { RefreshToken = "refresh_token" }; var child = new GrantedToken { ParentTokenId = "refresh_token", AccessToken = "access_token_child" }; var parameter = new RevokeTokenParameter { Token = "refresh_token" }; _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(new AuthenticateInstruction()); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null)) .Returns(() => Task.FromResult(new AuthenticationResult(new Core.Common.Models.Client(), null))); _grantedTokenRepositoryStub.Setup(g => g.GetAccessToken(It.IsAny <string>())) .Returns(() => Task.FromResult((GrantedToken)null)); _grantedTokenRepositoryStub.Setup(g => g.GetRefreshToken(It.IsAny <string>())) .Returns(Task.FromResult(parent)); _grantedTokenRepositoryStub.Setup(g => g.RemoveAccessToken(It.IsAny <string>())) .Returns(Task.FromResult(true)); // ACT await _revokeTokenAction.Execute(parameter, null, null, null); // ASSERTS _grantedTokenRepositoryStub.Verify(g => g.RemoveRefreshToken(parent.RefreshToken)); }
public async Task <bool> AddToken(GrantedToken grantedToken, CancellationToken cancellationToken) { var value = JsonConvert.SerializeObject(grantedToken); var existingScopeValue = await _database.StringGetAsync(grantedToken.ClientId + grantedToken.Scope) .ConfigureAwait(false); var existingScopeToken = existingScopeValue.HasValue ? JsonConvert.DeserializeObject <GrantedToken[]>(existingScopeValue) ! : Array.Empty <GrantedToken>(); var scopeTokens = JsonConvert.SerializeObject(existingScopeToken.Concat(new[] { grantedToken }).ToArray()); var expiry = TimeSpan.FromSeconds(grantedToken.ExpiresIn); var idTask = _database.StringSetAsync(grantedToken.Id, value, expiry, when: When.NotExists); var scopeTokenTask = _database.StringSetAsync( grantedToken.ClientId + grantedToken.Scope, scopeTokens, expiry, when: When.NotExists); var accessTokenTask = _database.StringSetAsync(grantedToken.AccessToken, value, expiry, when: When.NotExists); var refreshTokenTask = grantedToken.RefreshToken == null ? Task.FromResult(true) : _database.StringSetAsync(grantedToken.RefreshToken, value, expiry, when: When.NotExists); if ((await Task.WhenAll(idTask, scopeTokenTask, accessTokenTask, refreshTokenTask).ConfigureAwait(false)) .All(x => x)) { return(true); } return(await RemoveToken(grantedToken).ConfigureAwait(false)); }
private static GrantedToken GetGrantedToken(JwsPayload jwsPayload) { if (jwsPayload == null) { throw new ArgumentNullException(nameof(jwsPayload)); } var result = new GrantedToken { Scope = jwsPayload.GetClaimValue(StandardClaimNames.Scopes), ClientId = jwsPayload.GetClaimValue(StandardClaimNames.ClientId), ExpiresIn = (int)jwsPayload.ExpirationTime, TokenType = Constants.StandardTokenTypes.Bearer, IdTokenPayLoad = jwsPayload }; var issuedAt = jwsPayload.GetDoubleClaim(StandardClaimNames.Iat); if (issuedAt != default(double)) { result.CreateDateTime = issuedAt.UnixTimeStampToDateTime(); } return(result); }
public async Task <bool> AddToken(GrantedToken grantedToken) { if (grantedToken == null) { throw new ArgumentNullException(nameof(grantedToken)); } var id = Guid.NewGuid().ToString(); await _storage.SetAsync(id, grantedToken, grantedToken.ExpiresIn); // 1. Store tokens. await _storage.SetAsync("access_token_" + grantedToken.AccessToken, id, grantedToken.ExpiresIn); if (!string.IsNullOrWhiteSpace(grantedToken.IdToken)) { await _storage.SetAsync("access_token_" + grantedToken.IdToken, id, grantedToken.ExpiresIn); } await _storage.SetAsync("refresh_token_" + grantedToken.RefreshToken, id, grantedToken.ExpiresIn); var searchKey = GetSearchKey(grantedToken); var grantedTokens = await _storage.GetValue(searchKey); var values = new JArray(); if (!string.IsNullOrWhiteSpace(grantedTokens)) { values = JArray.Parse(grantedTokens); } values.Add(id); await _storage.SetAsync(searchKey, values.ToString(), grantedToken.ExpiresIn); // 2. Store search key. return(true); }
public GrantedTokenValidationResult CheckGrantedToken(GrantedToken grantedToken) { if (grantedToken == null) { return(new GrantedTokenValidationResult { MessageErrorCode = ErrorCodes.InvalidToken, MessageErrorDescription = ErrorDescriptions.TheTokenIsNotValid, IsValid = false }); } var expirationDateTime = grantedToken.CreateDateTime.AddSeconds(grantedToken.ExpiresIn); var tokenIsExpired = DateTime.UtcNow > expirationDateTime; if (tokenIsExpired) { return(new GrantedTokenValidationResult { MessageErrorCode = ErrorCodes.InvalidToken, MessageErrorDescription = ErrorDescriptions.TheTokenIsExpired, IsValid = false }); } return(new GrantedTokenValidationResult { IsValid = true }); }
public async Task <bool> AddToken(GrantedToken grantedToken) { if (grantedToken == null) { throw new ArgumentNullException(nameof(grantedToken)); } var refreshToken = await GetRefreshToken(grantedToken.RefreshToken); var accessToken = await GetAccessToken(grantedToken.AccessToken); if (refreshToken != null || accessToken != null) { return(false); } var tokens = await _storage.TryGetValueAsync <List <GrantedToken> >(GRANTED_TOKENS).ConfigureAwait(false); if (tokens == null) { tokens = new List <GrantedToken>(); } tokens.Add(grantedToken); await _storage.SetAsync(string.Format(ACCESS_TOKEN, grantedToken.AccessToken), grantedToken).ConfigureAwait(false); await _storage.SetAsync(string.Format(REFRESH_TOKEN, grantedToken.RefreshToken), grantedToken).ConfigureAwait(false); await _storage.SetAsync(GRANTED_TOKENS, tokens).ConfigureAwait(false); return(true); }
public async Task When_There_Is_No_Algorithm_Specified_Then_JwsPayload_Is_Returned() { // ARRANGE InitializeFakeObjects(); var grantedToken = new GrantedToken { UserInfoPayLoad = new JwsPayload() }; var client = new Client { UserInfoSignedResponseAlg = string.Empty }; _grantedTokenValidatorFake.Setup(g => g.CheckAccessTokenAsync(It.IsAny <string>())) .Returns(Task.FromResult(new GrantedTokenValidationResult { IsValid = true })); _tokenStoreFake.Setup(g => g.GetAccessToken(It.IsAny <string>())) .Returns(Task.FromResult(grantedToken)); _clientRepositoryFake.Setup(c => c.GetClientByIdAsync(It.IsAny <string>())) .Returns(Task.FromResult(client)); // ACT var result = await _getJwsPayload.Execute("access_token"); // ASSERT Assert.NotNull(result); }
public async Task When_Requesting_An_Existed_Granted_Token_Then_Check_Id_Token_Is_Signed_And_Encrypted() { // ARRANGE InitializeFakeObjects(); const string accessToken = "accessToken"; const string identityToken = "identityToken"; const string clientId = "clientId"; var authorizationCodeGrantTypeParameter = new AuthorizationCodeGrantTypeParameter { ClientAssertion = "clientAssertion", ClientAssertionType = "clientAssertionType", ClientSecret = "clientSecret", RedirectUri = "redirectUri", ClientId = clientId }; var result = new AuthenticationResult(new Core.Common.Models.Client { ClientId = "clientId", IdTokenSignedResponseAlg = Jwt.Constants.JwsAlgNames.RS256, IdTokenEncryptedResponseAlg = Jwt.Constants.JweAlgNames.RSA1_5, IdTokenEncryptedResponseEnc = Jwt.Constants.JweEncNames.A128CBC_HS256 }, null); var authorizationCode = new AuthorizationCode { ClientId = clientId, RedirectUri = "redirectUri", CreateDateTime = DateTime.UtcNow }; var grantedToken = new GrantedToken { ClientId = clientId, AccessToken = accessToken, IdToken = identityToken, IdTokenPayLoad = new JwsPayload() }; _clientValidatorFake.Setup(c => c.CheckPkce(It.IsAny<Client>(), It.IsAny<string>(), It.IsAny<AuthorizationCode>())) .Returns(true); _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny<AuthenticationHeaderValue>())) .Returns(new AuthenticateInstruction()); _authenticateClientFake.Setup(a => a.AuthenticateAsync(It.IsAny<AuthenticateInstruction>())) .Returns(Task.FromResult(result)); _authorizationCodeStoreFake.Setup(a => a.GetAuthorizationCode(It.IsAny<string>())) .Returns(Task.FromResult(authorizationCode)); _simpleIdentityServerConfiguratorFake.Setup(s => s.GetAuthorizationCodeValidityPeriodInSecondsAsync()) .Returns(Task.FromResult((double)3000)); _clientValidatorFake.Setup(c => c.GetRedirectionUrls(It.IsAny<Core.Common.Models.Client>(), It.IsAny<string>())) .Returns(new[] { "redirectUri" }); _grantedTokenHelperStub.Setup(g => g.GetValidGrantedTokenAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<JwsPayload>(), It.IsAny<JwsPayload>())) .Returns(Task.FromResult(grantedToken)); // ACT var r = await _getTokenByAuthorizationCodeGrantTypeAction.Execute(authorizationCodeGrantTypeParameter, null); // ASSERTS Assert.NotNull(r); }
public async Task <GrantedToken> GetToken(params string[] scopes) { try { await _semaphore.WaitAsync(); var allScopes = scopes.ToArray(); var token = _tokens.FirstOrDefault( t => allScopes.Length == t.Scopes.Count() && allScopes.All(s => t.Scopes.Contains(s))); if (token != null) { if (DateTime.UtcNow < token.ExpirationDateTime) { return(token.GrantedToken); } _tokens.Remove(token); } var grantedTokenResponse = await _identityServerClientFactory .CreateAuthSelector() .UseClientSecretPostAuth(_clientId, _clientSecret) .UseClientCredentials(allScopes.ToArray()) .ResolveAsync($"{_authority}/.well-known/uma2-configuration"); GrantedToken grantedToken = null; if (!string.IsNullOrWhiteSpace(grantedTokenResponse.Content.AccessToken)) { grantedToken = new GrantedToken { AccessToken = grantedTokenResponse.Content.AccessToken, ExpiresIn = grantedTokenResponse.Content.ExpiresIn, IdToken = grantedTokenResponse.Content.IdToken, RefreshToken = grantedTokenResponse.Content.RefreshToken, Scope = string.Join(",", grantedTokenResponse.Content.Scope), TokenType = grantedTokenResponse.Content.TokenType }; _tokens.Add(new StoredToken { GrantedToken = grantedToken, ExpirationDateTime = DateTime.UtcNow.AddSeconds(grantedTokenResponse.Content.ExpiresIn), Scopes = allScopes }); } return(grantedToken); } catch (Exception e) { throw; } finally { _semaphore.Release(); } }
public async Task When_Generating_AuthorizationResponse_With_AccessToken_And_ThereIs_A_GrantedToken_Then_Token_Is_Added_To_The_Parameters() { // ARRANGE InitializeFakeObjects(); const string idToken = "idToken"; const string clientId = "clientId"; const string scope = "openid"; var authorizationParameter = new AuthorizationParameter { ClientId = clientId, Scope = scope }; var grantedToken = new GrantedToken { AccessToken = Guid.NewGuid().ToString() }; var actionResult = new ActionResult { RedirectInstruction = new RedirectInstruction() }; var jwsPayload = new JwsPayload(); _parameterParserHelperFake.Setup(p => p.ParseResponseTypes(It.IsAny <string>())) .Returns(new List <ResponseType> { ResponseType.token }); _jwtGeneratorFake.Setup( j => j.GenerateIdTokenPayloadForScopesAsync(It.IsAny <IList <Claim> >(), It.IsAny <AuthorizationParameter>(), null, null)) .Returns(Task.FromResult(jwsPayload)); _jwtGeneratorFake.Setup( j => j.GenerateUserInfoPayloadForScopeAsync(It.IsAny <AuthorizationParameter>(), It.IsAny <IList <Claim> >())) .Returns(Task.FromResult(jwsPayload)); _jwtGeneratorFake.Setup(j => j.EncryptAsync(It.IsAny <string>(), It.IsAny <JweAlg>(), It.IsAny <JweEnc>())) .Returns(Task.FromResult(idToken)); _parameterParserHelperFake.Setup(p => p.ParseScopes(It.IsAny <string>())) .Returns(() => new List <string> { scope }); _grantedTokenHelperStub.Setup(r => r.GetValidGrantedTokenAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <JwsPayload>(), It.IsAny <JwsPayload>())) .Returns(() => Task.FromResult(grantedToken)); _resourceOwnerRepoStub.Setup(r => r.GetAsync(It.IsAny <string>())).Returns(Task.FromResult(new ResourceOwner { Claims = new List <Claim> { new Claim("sub", "fake") } })); // ACT await _generateAuthorizationResponse.ExecuteAsync(actionResult, authorizationParameter, new Client(), null, "fake"); // ASSERTS Assert.True(actionResult.RedirectInstruction.Parameters.Any(p => p.Name == Constants.StandardAuthorizationResponseNames.AccessTokenName)); Assert.True(actionResult.RedirectInstruction.Parameters.Any(p => p.Value == grantedToken.AccessToken)); }
public async Task When_Access_Is_Granted_Then_Token_Is_Returned() { // ARRANGE const string scope = "valid_scope"; const string clientId = "client_id"; const string accessToken = "access_token"; var scopes = new List <string> { scope }; InitializeFakeObjects(); var clientCredentialsGrantTypeParameter = new ClientCredentialsGrantTypeParameter { Scope = scope }; var client = new AuthenticationResult(new Core.Common.Models.Client { GrantTypes = new List <GrantType> { GrantType.client_credentials }, ResponseTypes = new List <ResponseType> { ResponseType.token }, ClientId = clientId }, null); var grantedToken = new GrantedToken { ClientId = clientId, AccessToken = accessToken, IdTokenPayLoad = new JwsPayload() }; var authenticateInstruction = new AuthenticateInstruction(); _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(authenticateInstruction); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null)) .Returns(Task.FromResult(client)); _scopeValidatorStub.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Core.Common.Models.Client>())) .Returns(() => new ScopeValidationResult(true) { Scopes = scopes }); _grantedTokenGeneratorHelperStub.Setup(g => g.GenerateTokenAsync(It.IsAny <Core.Common.Models.Client>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <JwsPayload>(), It.IsAny <JwsPayload>())) .Returns(Task.FromResult(grantedToken)); // ACT var result = await _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null, null, null); // ASSERTS _oauthEventSource.Verify(s => s.GrantAccessToClient(clientId, accessToken, scope)); Assert.NotNull(result); Assert.True(result.ClientId == clientId); }
public async Task WhenCheckingNullTokenThenTokenIsNotValid() { var jwksStoreMock = new Mock <IJwksStore>(); GrantedToken token = null; var result = await token.CheckGrantedToken(jwksStoreMock.Object).ConfigureAwait(false); Assert.False(result.IsValid); }
/// <inheritdoc /> public async Task <bool> AddToken(GrantedToken grantedToken, CancellationToken cancellationToken) { await using var session = _sessionFactory(); session.Store(grantedToken); await session.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return(true); }
public async Task <TokenResponse> PostToken() { var certificate = GetCertificate(); if (Request.Form == null) { throw new ArgumentNullException(nameof(Request.Form)); } var serializer = new ParamSerializer(); var tokenRequest = serializer.Deserialize <TokenRequest>(Request.Form); GrantedToken result = null; StringValues authorizationHeader; AuthenticationHeaderValue authenticationHeaderValue = null; if (Request.Headers.TryGetValue("Authorization", out authorizationHeader)) { var authorizationHeaderValue = authorizationHeader.First(); var splittedAuthorizationHeaderValue = authorizationHeaderValue.Split(' '); if (splittedAuthorizationHeaderValue.Count() == 2) { authenticationHeaderValue = new AuthenticationHeaderValue( splittedAuthorizationHeaderValue[0], splittedAuthorizationHeaderValue[1]); } } switch (tokenRequest.GrantType) { case GrantTypes.password: var resourceOwnerParameter = tokenRequest.ToResourceOwnerGrantTypeParameter(); result = await _tokenActions.GetTokenByResourceOwnerCredentialsGrantType(resourceOwnerParameter, authenticationHeaderValue, certificate); break; case GrantTypes.authorization_code: var authCodeParameter = tokenRequest.ToAuthorizationCodeGrantTypeParameter(); result = await _tokenActions.GetTokenByAuthorizationCodeGrantType( authCodeParameter, authenticationHeaderValue); break; case GrantTypes.refresh_token: var refreshTokenParameter = tokenRequest.ToRefreshTokenGrantTypeParameter(); result = await _tokenActions.GetTokenByRefreshTokenGrantType(refreshTokenParameter); break; case GrantTypes.client_credentials: var clientCredentialsParameter = tokenRequest.ToClientCredentialsGrantTypeParameter(); result = await _tokenActions.GetTokenByClientCredentialsGrantType(clientCredentialsParameter, authenticationHeaderValue); break; } return(result.ToDto()); }
When_Generating_AuthorizationResponse_With_AccessToken_And_ThereIs_A_GrantedToken_Then_Token_Is_Added_To_The_Parameters() { const string clientId = "clientId"; const string scope = "openid"; var claimsIdentity = new ClaimsIdentity("fake"); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); var authorizationParameter = new AuthorizationParameter { ResponseType = ResponseTypeNames.Token, ClientId = clientId, Scope = scope }; var handler = new JwtSecurityTokenHandler(); var issuedAt = DateTime.UtcNow; const int expiresIn = 20000; var defaultSigningKey = await _inMemoryJwksRepository.GetDefaultSigningKey().ConfigureAwait(false); var accessToken = handler.CreateEncodedJwt( "test", clientId, claimsIdentity, null, issuedAt.AddSeconds(expiresIn), issuedAt, defaultSigningKey); var grantedToken = new GrantedToken { ClientId = clientId, AccessToken = accessToken, CreateDateTime = issuedAt, ExpiresIn = expiresIn }; _tokenStore.Setup( x => x.GetToken( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <JwtPayload>(), It.IsAny <JwtPayload>(), It.IsAny <CancellationToken>())) .ReturnsAsync(grantedToken); var actionResult = await _generateAuthorizationResponse.Generate( new EndpointResult { RedirectInstruction = new RedirectInstruction() }, authorizationParameter, claimsPrincipal, new Client { ClientId = clientId }, "test", CancellationToken.None) .ConfigureAwait(false); Assert.Equal( grantedToken.AccessToken, actionResult.RedirectInstruction !.Parameters .First(x => x.Name == StandardAuthorizationResponseNames.AccessTokenName) .Value); }
public async Task When_Passing_Active_AccessToken_Then_Result_Should_Be_Returned() { // ARRANGE InitializeFakeObjects(); const string clientId = "client_id"; const string subject = "subject"; const string audience = "audience"; var authenticationHeaderValue = new AuthenticationHeaderValue("Basic", "ClientId:ClientSecret".Base64Encode()); var audiences = new[] { audience }; var parameter = new IntrospectionParameter { TokenTypeHint = Constants.StandardTokenTypeHintNames.RefreshToken, Token = "token" }; var client = new AuthenticationResult(new Core.Common.Models.Client { ClientId = clientId }, null); var grantedToken = new GrantedToken { ClientId = clientId, IdTokenPayLoad = new JwsPayload { { Jwt.Constants.StandardResourceOwnerClaimNames.Subject, subject }, { StandardClaimNames.Audiences, audiences } }, CreateDateTime = DateTime.UtcNow, ExpiresIn = 20000 }; _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>(), null)) .Returns(Task.FromResult(client)); _tokenStoreStub.Setup(a => a.GetRefreshToken(It.IsAny <string>())) .Returns(() => Task.FromResult((GrantedToken)null)); _tokenStoreStub.Setup(a => a.GetAccessToken(It.IsAny <string>())) .Returns(() => Task.FromResult(grantedToken)); // ACT var result = await _postIntrospectionAction.Execute(parameter, authenticationHeaderValue, null); // ASSERTS Assert.NotNull(result); Assert.True(result.Active); Assert.True(result.Audience == audience); Assert.True(result.Subject == subject); }
public async Task <bool> Execute(RevokeTokenParameter revokeTokenParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName) { if (revokeTokenParameter == null) { throw new ArgumentNullException(nameof(revokeTokenParameter)); } if (string.IsNullOrWhiteSpace(revokeTokenParameter.Token)) { throw new ArgumentNullException(nameof(revokeTokenParameter.Token)); } // 1. Check the client credentials var errorMessage = string.Empty; var instruction = CreateAuthenticateInstruction(revokeTokenParameter, authenticationHeaderValue, certificate); var authResult = await _authenticateClient.AuthenticateAsync(instruction, issuerName); var client = authResult.Client; if (client == null) { throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage); } // 2. Retrieve the granted token & check if it exists GrantedToken grantedToken = await _tokenStore.GetAccessToken(revokeTokenParameter.Token); bool isAccessToken = true; if (grantedToken == null) { grantedToken = await _tokenStore.GetRefreshToken(revokeTokenParameter.Token); isAccessToken = false; } if (grantedToken == null) { throw new IdentityServerException(ErrorCodes.InvalidToken, ErrorDescriptions.TheTokenDoesntExist); } // 3. Verifies whether the token was issued to the client making the revocation request if (grantedToken.ClientId != client.ClientId) { throw new IdentityServerException(ErrorCodes.InvalidToken, string.Format(ErrorDescriptions.TheTokenHasNotBeenIssuedForTheGivenClientId, client.ClientId)); } // 4. Invalid the granted token if (isAccessToken) { return(await _tokenStore.RemoveAccessToken(grantedToken.AccessToken)); } return(await _tokenStore.RemoveRefreshToken(grantedToken.RefreshToken)); }
public static async Task <GrantedTokenValidationResult> CheckGrantedToken(this GrantedToken grantedToken, IJwksStore jwksStore, CancellationToken cancellationToken = default) { if (grantedToken == null) { return(new GrantedTokenValidationResult { MessageErrorCode = ErrorCodes.InvalidToken, MessageErrorDescription = Strings.TheTokenIsNotValid, IsValid = false }); } var expirationDateTime = grantedToken.CreateDateTime.AddSeconds(grantedToken.ExpiresIn); var tokenIsExpired = DateTimeOffset.UtcNow > expirationDateTime; if (tokenIsExpired) { return(new GrantedTokenValidationResult { MessageErrorCode = ErrorCodes.InvalidToken, MessageErrorDescription = Strings.TheTokenIsExpired, IsValid = false }); } var publicKeys = await jwksStore.GetPublicKeys(cancellationToken).ConfigureAwait(false); var handler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { ValidateActor = false, ValidAudience = grantedToken.ClientId, ValidateIssuer = false, IssuerSigningKeys = publicKeys.Keys }; try { handler.ValidateToken(grantedToken.AccessToken, validationParameters, out _); return(new GrantedTokenValidationResult { IsValid = true }); } catch (Exception exception) { return(new GrantedTokenValidationResult { IsValid = false, MessageErrorCode = exception.Message, MessageErrorDescription = exception.Message }); } }
private async Task <bool> RemoveToken(GrantedToken grantedToken) { var idTask = _database.KeyDeleteAsync(grantedToken.Id); var scopeTokenTask = _database.KeyDeleteAsync(grantedToken.ClientId + grantedToken.Scope); var accessTokenTask = _database.KeyDeleteAsync(grantedToken.AccessToken); var refreshTokenTask = grantedToken.RefreshToken == null ? Task.FromResult(true) : _database.KeyDeleteAsync(grantedToken.RefreshToken); return((await Task.WhenAll(idTask, scopeTokenTask, accessTokenTask, refreshTokenTask).ConfigureAwait(false)) .All(x => x)); }
public static GrantedTokenResponse ToDto(this GrantedToken grantedToken) { return(new() { AccessToken = grantedToken.AccessToken, IdToken = grantedToken.IdToken, ExpiresIn = grantedToken.ExpiresIn, RefreshToken = grantedToken.RefreshToken, TokenType = grantedToken.TokenType, Scope = string.Join(' ', grantedToken.Scope) }); }
public async Task <bool> Execute(RevokeTokenParameter revokeTokenParameter, AuthenticationHeaderValue authenticationHeaderValue) { if (revokeTokenParameter == null) { throw new ArgumentNullException(nameof(revokeTokenParameter)); } if (string.IsNullOrWhiteSpace(revokeTokenParameter.Token)) { throw new ArgumentNullException(nameof(revokeTokenParameter.Token)); } // 1. Check the client credentials var errorMessage = string.Empty; var instruction = CreateAuthenticateInstruction(revokeTokenParameter, authenticationHeaderValue); var authResult = await _authenticateClient.AuthenticateAsync(instruction); var client = authResult.Client; if (client == null) { client = await _clientRepository.GetClientByIdAsync(Constants.AnonymousClientId); if (client == null) { throw new IdentityServerException(ErrorCodes.InternalError, string.Format(ErrorDescriptions.ClientIsNotValid, Constants.AnonymousClientId)); } } // 2. Retrieve the granted token & check if it exists GrantedToken grantedToken = await _grantedTokenRepository.GetTokenAsync(revokeTokenParameter.Token); if (grantedToken == null) { grantedToken = await _grantedTokenRepository.GetTokenByRefreshTokenAsync(revokeTokenParameter.Token); } if (grantedToken == null) { return(false); } // 3. Verifies whether the token was issued to the client making the revocation request if (grantedToken.ClientId != client.ClientId) { throw new IdentityServerException(ErrorCodes.InvalidToken, string.Format(ErrorDescriptions.TheTokenHasNotBeenIssuedForTheGivenClientId, client.ClientId)); } // 4. Invalid the granted token return(await _grantedTokenRepository.DeleteAsync(grantedToken)); }
public string GetPayload(GrantedToken parameter) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } var result = new Payload { Content = parameter }; return(JsonConvert.SerializeObject(result)); }
public static GrantedTokenResponse ToDto(this GrantedToken grantedToken) { if (grantedToken == null) { throw new ArgumentNullException(nameof(grantedToken)); } return(new GrantedTokenResponse { AccessToken = grantedToken.AccessToken, IdToken = grantedToken.IdToken, ExpiresIn = grantedToken.ExpiresIn, RefreshToken = grantedToken.RefreshToken, TokenType = grantedToken.TokenType, Scope = grantedToken.Scope.Split(' ').ToList() }); }
public async Task When_Checking_Valid_Access_Token_Then_True_Is_Returned() { // ARRANGE InitializeFakeObjects(); var grantedToken = new GrantedToken { CreateDateTime = DateTime.UtcNow, ExpiresIn = 200000 }; _grantedTokenRepositoryStub.Setup(g => g.GetAccessToken(It.IsAny <string>())) .Returns(Task.FromResult(grantedToken)); // ACT var result = await _grantedTokenValidator.CheckAccessTokenAsync("access_token"); // ASSERT Assert.True(result.IsValid); }