public void Create(AuthenticationTokenCreateContext context)
        {
            var audienceId = context.Ticket.Properties.Dictionary["audience"];

            if (string.IsNullOrEmpty(audienceId) || AudiencesStore.FindAudience(audienceId) == null)
            {
                return;
            }

            // maybe only create a handle the first time, then re-use for same client
            // copy properties and set the desired lifetime of refresh token
            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                IssuedUtc  = context.Ticket.Properties.IssuedUtc,
                ExpiresUtc = JwtConfigurationProvider.RefreshTokenExpiresUtc
            };

            context.Ticket.Properties.IssuedUtc  = refreshTokenProperties.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = refreshTokenProperties.ExpiresUtc;

            var refreshTokenId     = Guid.NewGuid().ToString("n");
            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            _refreshTokens.TryAdd(refreshTokenId, refreshTokenTicket);

            // consider storing only the hash of the handle
            context.SetToken(refreshTokenId);
        }
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            if (string.IsNullOrWhiteSpace(this.audienceId))
            {
                throw new InvalidOperationException("AuthenticationTicket. Properties does not include audience");
            }

            Audience audience           = AudiencesStore.FindAudience(this.audienceId);
            var      securityKey        = GetSymmetricSecurityKey(audience);
            var      signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var claims  = data.Identity.Claims;
            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            if (!issued.HasValue || !expires.HasValue)
            {
                return(null);
            }

            var token        = new JwtSecurityToken(this.issuer, this.audienceId, claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwt          = tokenHandler.WriteToken(token);

            return(jwt);
        }
示例#3
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            var clientId     = string.Empty;
            var clientSecret = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return(Task.FromResult <object>(null));
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("invalid_clientId", $"Invalid client_id '{context.ClientId}'");
                return(Task.FromResult <object>(null));
            }

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        public AuthenticationTicket Unprotect(string protectedText)
        {
            if (string.IsNullOrWhiteSpace(protectedText))
            {
                throw new ArgumentNullException("protectedText");
            }

            var handler = new JwtSecurityTokenHandler();
            var token   = handler.ReadToken(protectedText) as JwtSecurityToken;

            if (token == null)
            {
                throw new ArgumentOutOfRangeException("protectedText", "Invalid JWT Token");
            }

            Audience audience             = AudiencesStore.FindAudience(this.audienceId);
            var      validationParameters = new TokenValidationParameters
            {
                IssuerSigningKey         = GetSymmetricSecurityKey(audience),
                ValidAudiences           = new[] { audience.AudienceId },
                ValidateIssuer           = true,
                ValidIssuer              = this.issuer,
                ValidateLifetime         = true,
                ValidateAudience         = true,
                ValidateIssuerSigningKey = true
            };

            var           tokenHandler   = new JwtSecurityTokenHandler();
            SecurityToken validatedToken = null;

            ClaimsPrincipal claimsPrincipal = tokenHandler.ValidateToken(protectedText, validationParameters, out validatedToken);
            var             claimsIdentity  = (ClaimsIdentity)claimsPrincipal.Identity;

            var authenticationExtra = new AuthenticationProperties(new Dictionary <string, string>());

            if (claimsIdentity.Claims.Any(c => c.Type == ExpiryClaimName))
            {
                string expiryClaim = (from c in claimsIdentity.Claims where c.Type == ExpiryClaimName select c.Value).Single();
                authenticationExtra.ExpiresUtc = epoch.AddSeconds(Convert.ToInt64(expiryClaim, CultureInfo.InvariantCulture));
            }

            if (claimsIdentity.Claims.Any(c => c.Type == IssuedAtClaimName))
            {
                string issued = (from c in claimsIdentity.Claims where c.Type == IssuedAtClaimName select c.Value).Single();
                authenticationExtra.IssuedUtc = epoch.AddSeconds(Convert.ToInt64(issued, CultureInfo.InvariantCulture));
            }

            var returnedIdentity = new ClaimsIdentity(claimsIdentity.Claims, "JWT");

            return(new AuthenticationTicket(returnedIdentity, authenticationExtra));
        }