public async Task <IActionResult> Create([FromBody] CredModel model,
                                                 [FromServices] IRequestClient <AuthValidationMQRequest> authValidationReqClient,
                                                 [FromServices] IRequestClient <UserClaimsMQRequest> userClaimsReqClient,
                                                 [FromServices] IGenerateRefreshTokenCommand generateRefreshTokenCommand)
        {
            string correlationId = null;

            try
            {
                if (model == null)
                {
                    return(BadRequest("Something went wrong"));
                }
                correlationId = Guid.NewGuid().ToString("N");

                // Validate username and password.
                Response <AuthValidationMQResponse> authValidationResponse = await authValidationReqClient.GetResponse <AuthValidationMQResponse>(new AuthValidationMQRequest()
                {
                    CorrelationId   = correlationId,
                    UsernameOrEmail = model.Username,
                    Password        = model.Password
                });

                if (authValidationResponse.Message.OpSuccess != true)
                {
                    throw new Exception("Error with authValidationReqClient request");
                }

                if (!authValidationResponse.Message.IsValid)
                {
                    return(BadRequest("Invalid username or password"));
                }

                // Get user and generate user claims.
                Response <UserClaimsMQResponse> claimsResponse = await userClaimsReqClient.GetResponse <UserClaimsMQResponse>(new UserClaimsMQRequest()
                {
                    CorrelationId   = correlationId,
                    AccountId       = authValidationResponse.Message.AccountId,
                    ClaimsConsumers = model.ClaimsConsumers
                });

                if (claimsResponse.Message.OpSuccess != true)
                {
                    throw new Exception("Error with userClaimsReqClient request");
                }

                // Generate refresh token.
                var claims = claimsResponse.Message.GetClaims();

                var req = ControllerContext.HttpContext.Request;
                TokenAdditionalData additionalData = new TokenAdditionalData()
                {
                    DeviceInfo    = "Device info",
                    RequesterIPv4 = "ipv4",
                    RequesterIPv6 = "ipv6"
                };

                TokenResult rTokenResult = await generateRefreshTokenCommand.Execute(authValidationResponse.Message.AccountId, claims, additionalData);

                return(Created("", rTokenResult));
            }
            catch (Exception ex)
            {
                if (model != null)
                {
                    model.Password = "******";
                }

                //Log error
                _logger.LogError("RefreshTokenController.Create", "Exception was thrown", new
                {
                    CorrelationId = correlationId,
                    CredModel     = model,
                    Exception     = ex
                });

                return(BadRequest("Something went wrong"));
            }
        }
Beispiel #2
0
        public async Task <TokenResult> Execute(string accountId, List <Claim> claims, TokenAdditionalData additionalData, DateTime?customExpireDate = null)
        {
            try
            {
                SymmetricSecurityKey key   = _symmetricKeyProvider.GetKey();
                SigningCredentials   creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //Generate and add token Jti claim. Will be used in short tokens to identify the creator refresh token
                string tokenJti = _tokenIdGenerator.Generate();
                claims.Add(new Claim(JwtRegisteredClaimNames.Jti, tokenJti));

                //Set expire date
                DateTime expireDate;
                if (customExpireDate != null)
                {
                    expireDate = customExpireDate.Value;
                }
                else
                {
                    expireDate = DateTime.Now.AddMinutes(_rTokenConfig.ExpiresInMin);
                }

                JwtSecurityToken jwtTokenOptions = new JwtSecurityToken(
                    issuer: _rTokenConfig.ValidIssuer,
                    audience: _rTokenConfig.ValidAudience,
                    claims: claims,
                    expires: expireDate,
                    signingCredentials: creds
                    );

                //Generate token string
                string token = new JwtSecurityTokenHandler().WriteToken(jwtTokenOptions);

                //Create token db record
                AccountRTokenInfo accountRTokenInfo = new AccountRTokenInfo()
                {
                    TokenId       = tokenJti,
                    AccountId     = accountId,
                    ExpireDate    = expireDate,
                    Status        = AccountRTokenStatus.Active,
                    CreateDate    = DateTime.Now,
                    DeviceInfo    = additionalData.DeviceInfo,
                    RequesterIPv4 = additionalData.RequesterIPv4,
                    RequesterIPv6 = additionalData.RequesterIPv6
                };

                //Save token db record
                await _accountRTokenRepo.InsertOneAsync(accountRTokenInfo);

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

                throw;
            }
        }
        public async Task <IActionResult> Renew([FromBody] RTokenRenewModel renewModel,
                                                [FromServices] IRequestClient <UserClaimsMQRequest> userClaimsReqClient,
                                                [FromServices] IGenerateRefreshTokenCommand generateRefreshTokenCommand,
                                                [FromServices] ITokenExtractor refreshTokenExtractor)
        {
            string correlationId = null;

            try
            {
                if (renewModel == null)
                {
                    return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
                }
                correlationId = Guid.NewGuid().ToString("N");

                //Old token verification and accountId retrieval goes here
                if (!refreshTokenExtractor.TryExractToken(renewModel.OldRToken, out List <Claim> oldClaims))
                {
                    return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
                }

                string accountId = oldClaims.Single(x => x.Type == "Account").Value;
                //Problem with dates
                DateTime expiredOld = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds((long.Parse(oldClaims.Single(x => x.Type == "exp").Value)));

                //Get user and generate user claims
                Response <UserClaimsMQResponse> claimsResp = await userClaimsReqClient.GetResponse <UserClaimsMQResponse>(new UserClaimsMQRequest()
                {
                    CorrelationId   = correlationId,
                    AccountId       = accountId,
                    ClaimsConsumers = renewModel.ClaimsConsumers
                });

                if (claimsResp.Message.OpSuccess != true)
                {
                    throw new Exception("Error with userClaimsReqClient request");
                }

                //Generate refresh token
                var newClaims = claimsResp.Message.GetClaims();

                var req = ControllerContext.HttpContext.Request;
                TokenAdditionalData additionalData = new TokenAdditionalData()
                {
                    DeviceInfo    = "Device info",
                    RequesterIPv4 = "ipv4",
                    RequesterIPv6 = "ipv6"
                };

                TokenResult rTokenResult = await generateRefreshTokenCommand.Execute(accountId, newClaims, additionalData, expiredOld);

                return(Created("", rTokenResult));
            }
            catch (Exception ex)
            {
                //Log error
                _logger.LogError("RefreshTokenController.Renew", "Exception was thrown", new
                {
                    CorrelationId   = correlationId,
                    TokenRenewModel = renewModel,
                    Exception       = ex
                });

                return(BadRequest(ValueResponse <TokenResult> .GeneralError("Something went wrong")));
            }
        }