Example #1
0
        public async Task AddParameters_AddsAccessTokenToResponse_WhenAccessTokenIsEmitted()
        {
            // Arrange
            var provider = new DefaultTokenResponseParameterProvider(new TimeStampManager());
            var response = new OpenIdConnectMessage();

            var context = new TokenGeneratingContext(
                new ClaimsPrincipal(),
                new ClaimsPrincipal(),
                new OpenIdConnectMessage(),
                new RequestGrants()
            {
                Scopes = new[] { ApplicationScope.OpenId, new ApplicationScope("resourceId", "read") }
            });

            context.InitializeForToken(TokenTypes.AccessToken);
            context.AddToken(new TokenResult(new TestToken(TokenTypes.AccessToken), "serialized_access_token"));

            // Act
            await provider.AddParameters(context, response);

            // Assert
            Assert.Equal("serialized_access_token", response.AccessToken);
            Assert.Equal("3600", response.ExpiresIn);
            Assert.True(response.Parameters.ContainsKey("expires_on"));
            Assert.Equal("946688400", response.Parameters["expires_on"]);
            Assert.True(response.Parameters.ContainsKey("not_before"));
            Assert.Equal("946684800", response.Parameters["not_before"]);
            Assert.Equal("resourceId", response.Resource);
            Assert.Equal("Bearer", response.TokenType);
        }
        public async Task DefaultTokenClaimsManager_CallsProviders_InAscendingOrderAsync()
        {
            // Arrange
            var context     = new TokenGeneratingContext(new ClaimsPrincipal(), new ClaimsPrincipal(), new OpenIdConnectMessage(), new RequestGrants());
            var resultsList = new List <string>();

            var firstProvider = new Mock <ITokenClaimsProvider>();

            firstProvider.SetupGet(p => p.Order).Returns(100);
            firstProvider.Setup(p => p.OnGeneratingClaims(It.IsAny <TokenGeneratingContext>()))
            .Callback(() => resultsList.Add("first"))
            .Returns(Task.CompletedTask);

            var secondProvider = new Mock <ITokenClaimsProvider>();

            secondProvider.SetupGet(p => p.Order).Returns(101);
            secondProvider.Setup(p => p.OnGeneratingClaims(It.IsAny <TokenGeneratingContext>()))
            .Callback(() => resultsList.Add("second"))
            .Returns(Task.CompletedTask);

            var manager = new DefaultTokenClaimsManager(new[] { secondProvider.Object, firstProvider.Object });

            // Act
            await manager.CreateClaimsAsync(context);

            // Assert
            Assert.Equal(new List <string> {
                "first", "second"
            }, resultsList);
        }
Example #3
0
 public async Task CreateClaimsAsync(TokenGeneratingContext context)
 {
     foreach (var provider in _providers)
     {
         await provider.OnGeneratingClaims(context);
     }
 }
        public async Task CreateTokenResponse_CallsParameterProvidersInOrder()
        {
            // Arrange
            var context     = new TokenGeneratingContext(new ClaimsPrincipal(), new ClaimsPrincipal(), new OpenIdConnectMessage(), new RequestGrants());
            var resultsList = new List <string>();

            var firstProvider = new Mock <ITokenResponseParameterProvider>();

            firstProvider.SetupGet(p => p.Order).Returns(100);
            firstProvider.Setup(p => p.AddParameters(It.IsAny <TokenGeneratingContext>(), It.IsAny <OpenIdConnectMessage>()))
            .Callback(() => resultsList.Add("first"))
            .Returns(Task.CompletedTask);

            var secondProvider = new Mock <ITokenResponseParameterProvider>();

            secondProvider.SetupGet(p => p.Order).Returns(101);
            secondProvider.Setup(p => p.AddParameters(It.IsAny <TokenGeneratingContext>(), It.IsAny <OpenIdConnectMessage>()))
            .Callback(() => resultsList.Add("second"))
            .Returns(Task.CompletedTask);

            var responseFactory = new DefaultTokenResponseFactory(new[] { secondProvider.Object, firstProvider.Object });

            // Act
            var response = await responseFactory.CreateTokenResponseAsync(context);

            // Assert
            Assert.Equal(new List <string> {
                "first", "second"
            }, resultsList);
        }
        public async Task AddParameters_AddsIdTokenToResponse_WhenIdTokenIsEmitted()
        {
            // Arrange
            var provider = new DefaultAuthorizationResponseParameterProvider(new TimeStampManager());
            var response = new AuthorizationResponse()
            {
                Message      = new OpenIdConnectMessage(),
                RedirectUri  = "http://www.example.com/callback",
                ResponseMode = "query"
            };

            var context = new TokenGeneratingContext(
                new ClaimsPrincipal(),
                new ClaimsPrincipal(),
                new OpenIdConnectMessage()
            {
                State = "state"
            },
                new RequestGrants());

            context.InitializeForToken(TokenTypes.IdToken);
            context.AddToken(new TokenResult(new TestToken(TokenTypes.IdToken), "serialized_id_token"));

            // Act
            await provider.AddParameters(context, response);

            // Assert
            Assert.Equal("state", response.Message.State);
            Assert.Equal("serialized_id_token", response.Message.IdToken);
        }
        public async Task IssueAccessTokenAsync(TokenGeneratingContext context)
        {
            var accessToken = await CreateAccessTokenAsync(context);

            var subjectIdentity = CreateSubject(accessToken);

            var descriptor = new SecurityTokenDescriptor();

            descriptor.Issuer    = accessToken.Issuer;
            descriptor.Audience  = accessToken.Audience;
            descriptor.Subject   = subjectIdentity;
            descriptor.Expires   = accessToken.Expires.UtcDateTime;
            descriptor.NotBefore = accessToken.NotBefore.UtcDateTime;

            var credentialsDescriptor = await _credentialsProvider.GetSigningCredentialsAsync();

            descriptor.SigningCredentials = credentialsDescriptor.Credentials;

            var token = _handler.CreateJwtSecurityToken(descriptor);

            token.Payload.Remove(IdentityServiceClaimTypes.JwtId);
            token.Payload.Remove(IdentityServiceClaimTypes.IssuedAt);
            //token.Payload.Add(IdentityServiceClaimTypes.JwtId, accessToken.Id);

            context.AddToken(new TokenResult(accessToken, _handler.WriteToken(token), TokenKinds.Bearer));
        }
Example #7
0
        public async Task IssueTokensAsync(TokenGeneratingContext context)
        {
            if (context.RequestGrants.Tokens.Contains(TokenTypes.AuthorizationCode))
            {
                context.InitializeForToken(TokenTypes.AuthorizationCode);
                await _codeIssuer.CreateAuthorizationCodeAsync(context);
            }

            if (context.RequestGrants.Tokens.Contains(TokenTypes.AccessToken))
            {
                context.InitializeForToken(TokenTypes.AccessToken);
                await _accessTokenIssuer.IssueAccessTokenAsync(context);
            }

            if (context.RequestGrants.Tokens.Contains(TokenTypes.IdToken))
            {
                context.InitializeForToken(TokenTypes.IdToken);
                await _idTokenIssuer.IssueIdTokenAsync(context);
            }

            if (context.RequestGrants.Tokens.Contains(TokenTypes.RefreshToken))
            {
                context.InitializeForToken(TokenTypes.RefreshToken);
                await _refreshTokenIssuer.IssueRefreshTokenAsync(context);
            }
        }
Example #8
0
        private async Task <RefreshToken> CreateRefreshTokenAsync(TokenGeneratingContext context)
        {
            await _claimsManager.CreateClaimsAsync(context);

            var claims = context.CurrentClaims;

            return(new RefreshToken(claims));
        }
Example #9
0
        public async Task IssueRefreshTokenAsync(TokenGeneratingContext context)
        {
            var refreshToken = await CreateRefreshTokenAsync(context);

            var token = _dataFormat.Protect(refreshToken);

            context.AddToken(new TokenResult(refreshToken, token));
        }
Example #10
0
        public async Task <OpenIdConnectMessage> CreateTokenResponseAsync(TokenGeneratingContext context)
        {
            var response = new OpenIdConnectMessage();

            foreach (var provider in _providers)
            {
                await provider.AddParameters(context, response);
            }

            return(response);
        }
        public async Task CreateAuthorizationCodeAsync(TokenGeneratingContext context)
        {
            await _claimsManager.CreateClaimsAsync(context);

            var claims = context.CurrentClaims;

            var code = new AuthorizationCode(claims);

            var tokenResult = new TokenResult(code, _dataFormat.Protect(code));

            context.AddToken(tokenResult);
        }
        public async Task <AuthorizationResponse> CreateAuthorizationResponseAsync(TokenGeneratingContext context)
        {
            var result = new AuthorizationResponse();

            result.Message      = new OpenIdConnectMessage();
            result.ResponseMode = context.RequestGrants.ResponseMode;
            result.RedirectUri  = context.RequestGrants.RedirectUri;

            foreach (var provider in _providers)
            {
                await provider.AddParameters(context, result);
            }

            return(result);
        }
Example #13
0
        public async Task IssueIdTokenAsync(TokenGeneratingContext context)
        {
            var idToken = await CreateIdTokenAsync(context);

            var subjectIdentity = CreateSubject(idToken);

            var descriptor = new SecurityTokenDescriptor();

            descriptor.Issuer    = idToken.Issuer;
            descriptor.Audience  = idToken.Audience;
            descriptor.Subject   = subjectIdentity;
            descriptor.IssuedAt  = idToken.IssuedAt.UtcDateTime;
            descriptor.Expires   = idToken.Expires.UtcDateTime;
            descriptor.NotBefore = idToken.NotBefore.UtcDateTime;

            var credentialsDescriptor = await _credentialsProvider.GetSigningCredentialsAsync();

            descriptor.SigningCredentials = credentialsDescriptor.Credentials;

            var token = _handler.CreateJwtSecurityToken(descriptor);

            token.Payload.Remove(IdentityServiceClaimTypes.JwtId);
            //token.Payload.Add(IdentityServiceClaimTypes.JwtId, idToken.Id);

            if (idToken.Nonce != null)
            {
                token.Payload.AddClaim(new Claim(IdentityServiceClaimTypes.Nonce, idToken.Nonce));
            }

            if (idToken.CodeHash != null)
            {
                token.Payload.AddClaim(new Claim(IdentityServiceClaimTypes.CodeHash, idToken.CodeHash));
            }

            if (idToken.AccessTokenHash != null)
            {
                token.Payload.AddClaim(new Claim(IdentityServiceClaimTypes.AccessTokenHash, idToken.AccessTokenHash));
            }

            context.AddToken(new TokenResult(idToken, _handler.WriteToken(token)));
        }
Example #14
0
        public Task AddParameters(TokenGeneratingContext context, OpenIdConnectMessage response)
        {
            if (context.IdToken != null)
            {
                response.IdToken = context.IdToken.SerializedValue;
                var expiresIn = _manager.GetDurationInSeconds(
                    context.IdToken.Token.Expires,
                    context.IdToken.Token.IssuedAt);

                response.Parameters.Add(
                    "id_token_expires_in",
                    expiresIn.ToString(CultureInfo.InvariantCulture));
            }

            if (context.AccessToken != null)
            {
                response.AccessToken = context.AccessToken.SerializedValue;
                response.ExpiresIn   = GetExpirationTime(context.AccessToken.Token);
                response.Parameters["expires_on"] = context.AccessToken.Token.GetClaimValue(IdentityServiceClaimTypes.Expires);
                response.Parameters["not_before"] = context.AccessToken.Token.GetClaimValue(IdentityServiceClaimTypes.NotBefore);
                response.Resource = context.RequestGrants.Scopes.First(s => s.ClientId != null).ClientId;
            }

            if (context.RefreshToken != null)
            {
                response.RefreshToken = context.RefreshToken.SerializedValue;
                var expiresIn = _manager.GetDurationInSeconds(
                    context.RefreshToken.Token.Expires,
                    context.RefreshToken.Token.IssuedAt);

                response.Parameters.Add(
                    "refresh_token_expires_in",
                    expiresIn.ToString(CultureInfo.InvariantCulture));
            }

            response.TokenType = "Bearer";
            return(Task.CompletedTask);
        }
        public Task AddParameters(TokenGeneratingContext context, AuthorizationResponse response)
        {
            if (context.AuthorizationCode != null)
            {
                response.Message.Code = context.AuthorizationCode.SerializedValue;
            }

            if (context.AccessToken != null)
            {
                response.Message.AccessToken = context.AccessToken.SerializedValue;
                response.Message.TokenType   = "Bearer";
                response.Message.ExpiresIn   = GetExpirationTime(context.AccessToken.Token);
                response.Message.Scope       = string.Join(" ", context.RequestGrants.Scopes.Select(s => s.Scope));
            }

            if (context.IdToken != null)
            {
                response.Message.IdToken = context.IdToken.SerializedValue;
            }

            response.Message.State = context.RequestParameters.State;
            return(Task.CompletedTask);
        }
Example #16
0
        public async Task AddParameters_AddsRefreshTokenToResponse_WhenRefreshTokenIsEmitted()
        {
            // Arrange
            var provider = new DefaultTokenResponseParameterProvider(new TimeStampManager());
            var response = new OpenIdConnectMessage();

            var context = new TokenGeneratingContext(
                new ClaimsPrincipal(),
                new ClaimsPrincipal(),
                new OpenIdConnectMessage(),
                new RequestGrants());

            context.InitializeForToken(TokenTypes.RefreshToken);
            context.AddToken(new TokenResult(new TestToken(TokenTypes.RefreshToken), "serialized_refresh_token"));

            // Act
            await provider.AddParameters(context, response);

            // Assert
            Assert.Equal("serialized_refresh_token", response.RefreshToken);
            Assert.True(response.Parameters.ContainsKey("refresh_token_expires_in"));
            Assert.Equal("3600", response.Parameters["refresh_token_expires_in"]);
            Assert.Equal("Bearer", response.TokenType);
        }
        public async Task AddParameters_AddsAccessTokenToResponse_WhenAccessTokenIsEmitted()
        {
            // Arrange
            var provider = new DefaultAuthorizationResponseParameterProvider(new TimeStampManager());
            var response = new AuthorizationResponse()
            {
                Message      = new OpenIdConnectMessage(),
                RedirectUri  = "http://www.example.com/callback",
                ResponseMode = "query"
            };

            var context = new TokenGeneratingContext(
                new ClaimsPrincipal(),
                new ClaimsPrincipal(),
                new OpenIdConnectMessage()
            {
                State = "state"
            },
                new RequestGrants()
            {
                Scopes = { ApplicationScope.OpenId, new ApplicationScope("resourceId", "read") }
            });

            context.InitializeForToken(TokenTypes.AccessToken);
            context.AddToken(new TokenResult(new TestToken(TokenTypes.AccessToken), "serialized_access_token"));

            // Act
            await provider.AddParameters(context, response);

            // Assert
            Assert.Equal("state", response.Message.State);
            Assert.Equal("serialized_access_token", response.Message.AccessToken);
            Assert.Equal("3600", response.Message.ExpiresIn);
            Assert.Equal("openid read", response.Message.Scope);
            Assert.Equal("Bearer", response.Message.TokenType);
        }