public async Task <Option <GrantedToken> > GetTokenByClientCredentialsGrantType( ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter, AuthenticationHeaderValue?authenticationHeaderValue, X509Certificate2?certificate, string issuerName, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(clientCredentialsGrantTypeParameter.Scope)) { return(new ErrorDetails { Status = HttpStatusCode.BadRequest, Title = ErrorCodes.InvalidRequest, Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.ScopeName) }); } // 1. Authenticate the client var instruction = authenticationHeaderValue.GetAuthenticateInstruction( clientCredentialsGrantTypeParameter, certificate); var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken) .ConfigureAwait(false); var client = authResult.Client; if (client == null) { return(new ErrorDetails { Status = HttpStatusCode.BadRequest, Title = ErrorCodes.InvalidClient, Detail = authResult.ErrorMessage ! });
public async Task When_ClientCredentialGrantType_Is_Not_Supported_Then_Exception_Is_Thrown() { // ARRANGE InitializeFakeObjects(); var clientCredentialsGrantTypeParameter = new ClientCredentialsGrantTypeParameter { Scope = "scope" }; var client = new AuthenticationResult(new Core.Common.Models.Client { GrantTypes = new List <GrantType> { GrantType.password } }, null); var authenticateInstruction = new AuthenticateInstruction(); _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(authenticateInstruction); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>())) .Returns(Task.FromResult(client)); // ACT & ASSERT var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null)); Assert.NotNull(exception); Assert.True(exception.Code == ErrorCodes.InvalidGrant); Assert.True(exception.Message == string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.Client.ClientId, GrantType.client_credentials)); }
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 <GrantedToken> GetTokenByClientCredentialsGrantType( ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate = null) { if (clientCredentialsGrantTypeParameter == null) { throw new ArgumentNullException(nameof(clientCredentialsGrantTypeParameter)); } var processId = Guid.NewGuid().ToString(); try { _eventPublisher.Publish(new GrantTokenViaClientCredentialsReceived(Guid.NewGuid().ToString(), processId, _payloadSerializer.GetPayload(clientCredentialsGrantTypeParameter, authenticationHeaderValue), authenticationHeaderValue, 0)); _simpleIdentityServerEventSource.StartGetTokenByClientCredentials(clientCredentialsGrantTypeParameter.Scope); _clientCredentialsGrantTypeParameterValidator.Validate(clientCredentialsGrantTypeParameter); var result = await _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, authenticationHeaderValue); _simpleIdentityServerEventSource.EndGetTokenByClientCredentials( result.ClientId, clientCredentialsGrantTypeParameter.Scope); _eventPublisher.Publish(new TokenGranted(Guid.NewGuid().ToString(), processId, _payloadSerializer.GetPayload(result), 1)); return(result); } catch (IdentityServerException ex) { _eventPublisher.Publish(new OpenIdErrorReceived(Guid.NewGuid().ToString(), processId, ex.Code, ex.Message, 1)); throw; } }
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 GrantTokenViaClientCredentialsReceived(string id, string processId, ClientCredentialsGrantTypeParameter parameter, AuthenticationHeaderValue authHeader, int order) { Id = id; ProcessId = processId; Parameter = parameter; AuthHeader = authHeader; Order = order; }
private AuthenticateInstruction CreateAuthenticateInstruction( ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue) { var result = _authenticateInstructionGenerator.GetAuthenticateInstruction(authenticationHeaderValue); result.ClientAssertion = clientCredentialsGrantTypeParameter.ClientAssertion; result.ClientAssertionType = clientCredentialsGrantTypeParameter.ClientAssertionType; result.ClientIdFromHttpRequestBody = clientCredentialsGrantTypeParameter.ClientId; result.ClientSecretFromHttpRequestBody = clientCredentialsGrantTypeParameter.ClientSecret; return(result); }
public void When_Scope_Is_Empty_Then_Exception_Is_Thrown() { // ARRANGE InitializeFakeObjects(); var parameter = new ClientCredentialsGrantTypeParameter(); // ACT & ASSERT var exception = Assert.Throws <IdentityServerException>(() => _clientCredentialsGrantTypeParameterValidator.Validate(parameter)); Assert.NotNull(exception); Assert.True(exception.Code == ErrorCodes.InvalidRequestCode); Assert.True(exception.Message == string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.ScopeName)); }
public void Validate(ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter) { if (clientCredentialsGrantTypeParameter == null) { throw new ArgumentNullException(nameof(clientCredentialsGrantTypeParameter)); } if (string.IsNullOrWhiteSpace(clientCredentialsGrantTypeParameter.Scope)) { throw new IdentityServerException( ErrorCodes.InvalidRequestCode, string.Format(ErrorDescriptions.MissingParameter, Constants.StandardTokenRequestParameterNames.ScopeName)); } }
public async Task When_Scope_Is_Not_Valid_Then_Exception_Is_Thrown() { // ARRANGE var messageDescription = "message_description"; 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 } }, null); var authenticateInstruction = new AuthenticateInstruction(); _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(authenticateInstruction); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>())) .Returns(Task.FromResult(client)); _clientValidatorStub.Setup(c => c.GetRedirectionUrls(It.IsAny <Client>(), It.IsAny <string[]>())).Returns(new string[0]); _scopeValidatorStub.Setup(s => s.Check(It.IsAny <string>(), It.IsAny <Core.Common.Models.Client>())) .Returns(() => new ScopeValidationResult(false) { ErrorMessage = messageDescription }); // ACT & ASSERT var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null)); Assert.NotNull(exception); Assert.True(exception.Code == ErrorCodes.InvalidScope); Assert.True(exception.Message == messageDescription); }
public async Task When_Client_Cannot_Be_Authenticated_Then_Exception_Is_Thrown() { // ARRANGE InitializeFakeObjects(); var clientCredentialsGrantTypeParameter = new ClientCredentialsGrantTypeParameter { Scope = "scope" }; var authenticateInstruction = new AuthenticateInstruction(); _authenticateInstructionGeneratorStub.Setup(a => a.GetAuthenticateInstruction(It.IsAny <AuthenticationHeaderValue>())) .Returns(authenticateInstruction); _authenticateClientStub.Setup(a => a.AuthenticateAsync(It.IsAny <AuthenticateInstruction>())) .Returns(() => Task.FromResult(new AuthenticationResult(null, null))); // ACT & ASSERT var exception = await Assert.ThrowsAsync <IdentityServerException>(() => _getTokenByClientCredentialsGrantTypeAction.Execute(clientCredentialsGrantTypeParameter, null)); Assert.NotNull(exception); Assert.True(exception.Code == ErrorCodes.InvalidClient); }
public async Task When_Getting_Token_Via_ClientCredentials_GrantType_Then_GrantedToken_Is_Returned() { const string scope = "valid_scope"; const string clientId = "valid_client_id"; var parameter = new ClientCredentialsGrantTypeParameter { Scope = scope }; var authenticationHeader = new AuthenticationHeaderValue( "Basic", $"{clientId}:{Clientsecret}".Base64Encode()); var result = await _tokenActions.GetTokenByClientCredentialsGrantType( parameter, authenticationHeader, null, null, CancellationToken.None) .ConfigureAwait(false) as Option <GrantedToken> .Result; Assert.Equal(clientId, result.Item.ClientId); }
public string GetPayload(ClientCredentialsGrantTypeParameter parameter, AuthenticationHeaderValue authenticationHeaderValue) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } var clientId = GetClientId(authenticationHeaderValue); if (string.IsNullOrWhiteSpace(clientId)) { clientId = parameter.ClientId; } var result = new Payload { ClientId = clientId, Authorization = BuildAuthHeader(authenticationHeaderValue), Content = parameter }; return(JsonConvert.SerializeObject(result)); }
public async Task <GrantedToken> Execute(ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter, AuthenticationHeaderValue authenticationHeaderValue, X509Certificate2 certificate, string issuerName) { if (clientCredentialsGrantTypeParameter == null) { throw new ArgumentNullException(nameof(clientCredentialsGrantTypeParameter)); } _clientCredentialsGrantTypeParameterValidator.Validate(clientCredentialsGrantTypeParameter); // 1. Authenticate the client var instruction = CreateAuthenticateInstruction(clientCredentialsGrantTypeParameter, authenticationHeaderValue, certificate); var authResult = await _authenticateClient.AuthenticateAsync(instruction, issuerName); var client = authResult.Client; if (client == null) { throw new IdentityServerException(ErrorCodes.InvalidClient, authResult.ErrorMessage); } // 2. Check client if (client.GrantTypes == null || !client.GrantTypes.Contains(GrantType.client_credentials)) { throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheGrantType, client.ClientId, GrantType.client_credentials)); } if (client.ResponseTypes == null || !client.ResponseTypes.Contains(ResponseType.token)) { throw new IdentityServerException(ErrorCodes.InvalidClient, string.Format(ErrorDescriptions.TheClientDoesntSupportTheResponseType, client.ClientId, ResponseType.token)); } // 3. Check scopes string allowedTokenScopes = string.Empty; if (!string.IsNullOrWhiteSpace(clientCredentialsGrantTypeParameter.Scope)) { var scopeValidation = _scopeValidator.Check(clientCredentialsGrantTypeParameter.Scope, client); if (!scopeValidation.IsValid) { throw new IdentityServerException( ErrorCodes.InvalidScope, scopeValidation.ErrorMessage); } allowedTokenScopes = string.Join(" ", scopeValidation.Scopes); } // 4. Generate the JWT access token on the fly. var grantedToken = await _grantedTokenHelper.GetValidGrantedTokenAsync(allowedTokenScopes, client.ClientId); if (grantedToken == null) { grantedToken = await _grantedTokenGeneratorHelper.GenerateTokenAsync(client, allowedTokenScopes, issuerName); await _tokenStore.AddToken(grantedToken); _oauthEventSource.GrantAccessToClient(client.ClientId, grantedToken.AccessToken, allowedTokenScopes); } return(grantedToken); }