Exemplo n.º 1
0
        public override async Task ReceiveMessage(IModel model, RefreshTokenRevokedEvent message, BasicDeliverEventArgs e, ILogger logger)
        {
            try
            {
                // Check if revoked token already exists in db.
                if (!(await _revokedTokenRepo.Exists(message.TokenId)))
                {
                    await _revokedTokenRepo.Add(message.TokenId, message.TokenId, message.Expires);

                    _logger.LogInfo("TokenRevokedEventRabbitMqConsumer.Consume", $"Token with key: {message.TokenId} added to revoked tokens.");
                }
                else
                {
                    _logger.LogError("TokenRevokedEventRabbitMqConsumer.Consume", $"Token with key: {message.TokenId} already exists.");
                }
            }
            catch (Exception ex)
            {
                // Log error.
                _logger.LogError("TokenRevokedEventRabbitMqConsumer.Consume", "Exception was thrown", new
                {
                    RefreshTokenRevokedEvent = message,
                    Exception = ex
                });
            }
        }
        public async Task <TokenResult> Execute(string refreshToken)
        {
            try
            {
                //1.Validate and extract refresh token
                if (!_refreshTokenExtracter.TryExractToken(refreshToken, out List <Claim> refreshTokenClaims))
                {
                    throw new InvalidTokenException("Jwt token is corrupted or expired");
                }

                string rTokenJti = refreshTokenClaims.Single(c => c.Type == JwtRegisteredClaimNames.Jti).Value;

                //2.Check if refresh token is revoked. If it is throw a security exception
                if (await _revokedTokenRepo.Exists(rTokenJti))
                {
                    throw new TokenRevokedException($"Token {rTokenJti} already revoked");
                }

                //3.Generate short token
                var key   = _symmetricKeyProvider.GetKey();
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //Create stoken claims using some claims from parent rtoken
                var shortTokenClaims = refreshTokenClaims.Where(c => c.Type == ClaimTypes.Name || c.Type == ClaimTypes.Role).Select(c => new Claim(c.Type, c.Value)).ToList();
                //Add token Jti claim
                string jti = _tokenIdGenerator.Generate();
                shortTokenClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, jti));
                //Add RefreshTokenId of the rtoken to the stoken claims as RefreshTokenId claim
                shortTokenClaims.Add(new Claim("rtokenjti", rTokenJti));

                JwtSecurityToken jwtTokenOptions = new JwtSecurityToken(
                    issuer: _shortTokenConfig.ValidIssuer,
                    audience: _shortTokenConfig.ValidAudience,
                    claims: shortTokenClaims,
                    expires: DateTime.Now.AddMinutes(_shortTokenConfig.ExpiresInMin),
                    signingCredentials: creds
                    );

                string shortToken = new JwtSecurityTokenHandler().WriteToken(jwtTokenOptions);

                return(new TokenResult(null, shortToken, jwtTokenOptions.ValidTo));
            }
            catch (Exception ex)
            {
                //Log error
                _logger.LogError("GenerateShortTokenCommand.Execute", "Exception was thrown", new
                {
                    Exception = ex
                });

                throw;
            }
        }