public async Task <ActionResult <TokenResponseDTO> > GetToken(LoginDTO credentials)
        {
            if (credentials == null)
            {
                return(BadRequest("No credentials were found"));
            }

            var user = await _userManager.FindByEmailAsync(credentials.Username);

            var refreshToken = await _tokenService.GenerateRefreshToken(user.Id);

            HttpContext.Response.Cookies.Append("MyKey", refreshToken.Token, new CookieOptions
            {
                HttpOnly    = true,
                Expires     = DateTimeOffset.FromUnixTimeMilliseconds(refreshToken.Expiration),
                IsEssential = true,
                SameSite    = SameSiteMode.None,
                Secure      = true
            });

            var accessToken = new TokenResponseDTO
            {
                Token = await _tokenService.RequestToken(credentials)
            };

            return(Ok(accessToken));
        }
        public async Task <ActionResult <TokenResponseDTO> > RefreshToken()
        {
            HttpContext.Request.Cookies.TryGetValue("MyKey", out var refreshToken);

            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                return(Unauthorized());
            }

            var hasValidRefreshToken = await _tokenService.CheckForValidRefreshToken(new RefreshToken { Token = refreshToken });

            if (!hasValidRefreshToken)
            {
                return(Unauthorized());
            }

            var token = await _context.RefreshTokens.FirstOrDefaultAsync(t => t.Token == refreshToken);

            var user = await _userManager.FindByIdAsync(token.UserId);

            var accessToken = new TokenResponseDTO
            {
                Token = await _tokenService.GenerateAccessToken(user.Email)
            };

            return(Ok(accessToken));
        }
예제 #3
0
 public override Task <TokenResponseDTO> GetByCode(CodeExchangeTokenRequestDTO request, ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         TokenResponseDTO response = new TokenResponseDTO();
         OpenOAuthProvider provider = new OpenOAuthProvider(request.Appid, request.Secret, request.Code, request.GrantType);
         if (!provider.OAuthAccess())
         {
             response.RetCode = "0500";
             response.RetMsg = provider.PromptInfo.CustomMessage;
             return response;
         }
         response.RetCode = "0000";
         response.RetMsg = "ok";
         response.Data = new TokenResponseDTO.Types.Result
         {
             Expires = provider.OAuthUser.Expire_In,
             Openid = provider.OAuthUser.Open_Id,
             RefreshExpires = provider.OAuthUser.Refresh_Expire_In,
             RefreshToken = provider.OAuthUser.Refresh_Token,
             Token = provider.OAuthUser.Token
         };
         return response;
     }));
 }
예제 #4
0
 public override Task <TokenResponseDTO> Refresh(TokenRefreshRequestDTO request, ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         TokenResponseDTO response = new TokenResponseDTO();
         RefreshTokenProvider refresh = new RefreshTokenProvider(request.Appid, request.RefreshToken);
         if (!refresh.Refresh())
         {
             response.RetMsg = refresh.PromptInfo.CustomMessage;
             response.RetCode = refresh.PromptInfo.ResultType <= 0 ? "0500" : ((int)refresh.PromptInfo.ResultType).ToString().PadLeft(4, '0');
             return response;
         }
         response.RetCode = "0000";
         response.RetMsg = "ok";
         response.Data = new TokenResponseDTO.Types.Result
         {
             RefreshToken = refresh.OAuthUser.Refresh_Token,
             Expires = refresh.OAuthUser.Expire_In,
             Openid = refresh.OAuthUser.Open_Id,
             RefreshExpires = refresh.OAuthUser.Refresh_Expire_In,
             Token = refresh.OAuthUser.Token
         };
         return response;
     }));
 }
예제 #5
0
        public async void Register_WithUniqueEmail_Ok()
        {
            // Arrange
            var client   = _server.Instance.CreateClient();
            var loginReq = new RegisterRequestDTO
            {
                ConfirmPassword = "******",
                Password        = "******",
                Email           = "*****@*****.**",
                UserName        = "******"
            };

            // Act
            var content = new StringContent(JsonConvert.SerializeObject(loginReq), Encoding.UTF8, "application/json");

            var response = await client.PostAsync("api/auth/register", content);

            var stream = await response.Content.ReadAsStreamAsync();

            TokenResponseDTO data = null;

            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                data = JsonConvert.DeserializeObject <TokenResponseDTO>(await reader.ReadToEndAsync());
            }

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(data.AccessToken);
            Assert.NotNull(data.RefreshToken);
        }
예제 #6
0
        public async Task <IActionResult> LoginAsync([FromBody] LoginRequestDTO login)
        {
            TokenModel token = await _authenticateBusiness.LoginAsync(_mapper.Map <LoginModel>(login));

            TokenResponseDTO response = _mapper.Map <TokenResponseDTO>(token);

            return(Ok(response));
        }
예제 #7
0
        public async Task <TokenResponseDTO> GeneraToken()
        {
            TokenResponseDTO tokenResponseDTO =
                new TokenResponseDTO {
                Process = false
            };

            var client = new HttpClient();
            //var disco = await client.GetDiscoveryDocumentAsync(options.UrlServer);

            var disco = await client.GetDiscoveryDocumentAsync(
                new DiscoveryDocumentRequest
            {
                Address = options.UrlServer,
                Policy  =
                {
                    RequireHttps = false
                }
            });

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return(tokenResponseDTO);
            }

            var tokenResponse = await client.RequestClientCredentialsTokenAsync(
                new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId     = options.ClienteId,
                ClientSecret = options.ClienteSecret,
                Scope        = options.ResourceAccess
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return(tokenResponseDTO);
            }
            tokenResponseDTO.Process = true;
            tokenResponseDTO.Token   = tokenResponse.AccessToken;

            return(tokenResponseDTO);
        }
예제 #8
0
        public ResponseResult <TokenResponseDTO> GetByCode(CodeExchangeTokenRequestDTO request)
        {
            OpenOAuthProvider provider = new OpenOAuthProvider(request.Appid, request.Secret, request.Code, request.GrantType);

            if (!provider.OAuthAccess())
            {
                return(Fail <TokenResponseDTO>(provider.PromptInfo.CustomMessage));
            }
            TokenResponseDTO response = new TokenResponseDTO
            {
                Expires        = provider.OAuthUser.Expire_In,
                Openid         = provider.OAuthUser.Open_Id,
                RefreshExpires = provider.OAuthUser.Refresh_Expire_In,
                RefreshToken   = provider.OAuthUser.Refresh_Token,
                Token          = provider.OAuthUser.Token
            };

            return(Success(response));
        }
예제 #9
0
        public async Task <TxResponseBE> Transferir(TxRequestBE txRequestBE)
        {
            var handler = new HttpClientHandler();

            handler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            var miHttpClient = new HttpClient(handler);

            TokenResponseDTO responseToken = await tokenAdapter.GeneraToken();

            var metadata = new Metadata();

            metadata.Add("Authorization", $"Bearer {responseToken.Token}");

            var channel = GrpcChannel.ForAddress
                              (configuration.GetValue <string>("UrlApiCliente"),
                              new GrpcChannelOptions {
                HttpClient = miHttpClient
            });

            BancaServiceGrpc.BancaServiceGrpcClient client =
                new BancaServiceGrpc.BancaServiceGrpcClient(channel);

            txRequest request = new txRequest()
            {
                IdCuentaDestino = txRequestBE.IdCuentaDestino,
                IdCuentaOrigen  = txRequestBE.IdCuentaOrigen,
                Monto           = (double)txRequestBE.Monto
            };
            txResponse response = await client.ProcesaTransaccionAsync
                                      (request, headers : metadata);

            TxResponseBE txResponseBE = new TxResponseBE()
            {
                Amount        = txRequestBE.Monto,
                Date          = DateTime.Now,
                OperationCode = response.IdOperacion
            };

            return(txResponseBE);
        }
예제 #10
0
        public ResponseResult <TokenResponseDTO> Refresh(TokenRefreshRequestDTO request)
        {
            RefreshTokenProvider refresh = new RefreshTokenProvider(request.Appid, request.RefreshToken);

            if (!refresh.Refresh())
            {
                return(Fail <TokenResponseDTO>(refresh.PromptInfo.CustomMessage));
            }

            TokenResponseDTO response = new TokenResponseDTO
            {
                RefreshToken   = refresh.OAuthUser.Refresh_Token,
                Expires        = refresh.OAuthUser.Expire_In,
                Openid         = refresh.OAuthUser.Open_Id,
                RefreshExpires = refresh.OAuthUser.Refresh_Expire_In,
                Token          = refresh.OAuthUser.Token
            };

            return(Success(response));
        }
예제 #11
0
        public async Task <TxResponseBE> Transferir(TxRequestBE txRequestBE)
        {
            string url  = configuration.GetValue <string>("UrlApiCliente");
            string ruta = url + "transaccion/ProcesarTx";
            //    + codCuenta.ToString();
            TokenResponseDTO responseToken = await tokenAdapter.GeneraToken();

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", responseToken.Token);

            StringContent content = new StringContent(JsonConvert.SerializeObject(txRequestBE), Encoding.UTF8, "application/json");

            var response = await client.PostAsync(ruta, content);

            TxResponseBE rpta =
                await response.Content.ReadAsAsync <TxResponseBE>();

            return(rpta);
        }
예제 #12
0
        public async Task <SaldoCuentaResponseBE> ConsultaSaldo(int codCuenta)
        {
            var handler = new HttpClientHandler();

            handler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            var miHttpClient = new HttpClient(handler);

            TokenResponseDTO responseToken = await tokenAdapter.GeneraToken();

            var metadata = new Metadata();

            metadata.Add("Authorization", $"Bearer {responseToken.Token}");

            var channel = GrpcChannel.ForAddress
                              (configuration.GetValue <string>("UrlApiCliente"),
                              new GrpcChannelOptions {
                HttpClient = miHttpClient
            });

            BancaServiceGrpc.BancaServiceGrpcClient client =
                new BancaServiceGrpc.BancaServiceGrpcClient(channel);

            CuentaRequest request = new CuentaRequest()
            {
                IdCuenta = codCuenta
            };
            CuentaResponse response = await client.ConsultarSaldoCtaAsync
                                          (request, headers : metadata);

            SaldoCuentaResponseBE txResponseBE = new SaldoCuentaResponseBE()
            {
                Amount = (decimal)response.Saldo,
                Date   = DateTime.Now
            };

            return(txResponseBE);
            //return null;
        }
        public TokenResponseDTO token([FromBody] TokenRequestDTO request)
        {
            var response = new TokenResponseDTO();
            var user     = _userService.LoginUser(request);

            if (!user.IsSuccess)
            {
                response.IsLogin = false;
                response.Message = user.Message;
                return(response);
            }

            var claims = new[]
            {
                new Claim("id", user.Data.UserId.ToString()),
                new Claim("date", new DateTime().ToString())
            };

            var secretBytes        = Encoding.UTF8.GetBytes(AuthenticationConstant.SecretKey);
            var key                = new SymmetricSecurityKey(secretBytes);
            var algorithm          = SecurityAlgorithms.HmacSha256;
            var signingCredentials = new SigningCredentials(key, algorithm);
            var expireDate         = DateTime.Now.AddDays(30);
            var token              = new JwtSecurityToken(
                AuthenticationConstant.Issuer,
                AuthenticationConstant.Audience,
                claims,
                notBefore: DateTime.Now,
                expires: expireDate,
                signingCredentials
                );

            response.IsLogin     = true;
            response.ExpireDate  = expireDate;
            response.Message     = "İşlem Başarılı";
            response.AccessToken = new JwtSecurityTokenHandler().WriteToken(token);
            return(response);
        }
예제 #14
0
        public ActionResult <Response <TokenResponseDTO> > Post([FromBody] CredentialsDTO dto,
                                                                [FromServices] SigningConfigurations signingConfigurations,
                                                                [FromServices] TokenConfigurations tokenConfigurations,
                                                                [FromServices] IMemoryCache cache)
        {
            if (dto == null ||
                (string.IsNullOrWhiteSpace(dto.UserID) && string.IsNullOrWhiteSpace(dto.SecretKey) && string.IsNullOrWhiteSpace(dto.RefreshToken)) ||
                (!string.IsNullOrWhiteSpace(dto.UserID) && !string.IsNullOrWhiteSpace(dto.SecretKey) && !string.IsNullOrWhiteSpace(dto.RefreshToken)) ||
                (string.IsNullOrWhiteSpace(dto.RefreshToken) && (string.IsNullOrWhiteSpace(dto.UserID) || string.IsNullOrWhiteSpace(dto.SecretKey))) ||
                (!string.IsNullOrWhiteSpace(dto.RefreshToken) && (!string.IsNullOrWhiteSpace(dto.UserID) || !string.IsNullOrWhiteSpace(dto.SecretKey)))
                )
            {
                return(BadRequest());
            }


            var watch = Stopwatch.StartNew();

            Response <TokenResponseDTO> result = new Response <TokenResponseDTO>();

            try
            {
                bool   isValidCredentials = false;
                string cachedUserId       = null;

                if (string.IsNullOrWhiteSpace(dto.RefreshToken))
                {
                    dto.SecretKey      = GetEncode512(dto.SecretKey);
                    isValidCredentials = _facade.Login(dto);
                }

                if (isValidCredentials ||
                    (cache.TryGetValue("refresh_token", out string cachedRefreshToken) && cache.TryGetValue("user_id", out cachedUserId) && cachedRefreshToken == dto.RefreshToken))
                {
                    ClaimsIdentity identity = new ClaimsIdentity(
                        new GenericIdentity(cachedUserId ?? dto.UserID, "Login"),
                        new[] {
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
                        new Claim(JwtRegisteredClaimNames.UniqueName, cachedUserId ?? dto.UserID)
                    }
                        );

                    var now           = DateTime.Now;
                    var cacheExpirate = now + TimeSpan.FromSeconds(tokenConfigurations.Seconds) * 2;

                    TokenResponseDTO tokenResponse = new TokenResponseDTO()
                    {
                        TokenExpirate        = tokenConfigurations.Seconds,
                        RefreshTokenExpirate = tokenConfigurations.Seconds * 2
                    };

                    var handler       = new JwtSecurityTokenHandler();
                    var securityToken = handler.CreateToken(new SecurityTokenDescriptor
                    {
                        Issuer             = tokenConfigurations.Issuer,
                        Audience           = tokenConfigurations.Audience,
                        SigningCredentials = signingConfigurations.SigningCredentials,
                        Subject            = identity,
                        NotBefore          = now,
                        Expires            = now + TimeSpan.FromSeconds(tokenConfigurations.Seconds)
                    });

                    tokenResponse.Token = handler.WriteToken(securityToken);

                    cache.Remove("refresh_token");
                    cache.Remove("user_id");

                    tokenResponse.RefreshToken = SetCache(cache, "refresh_token", Guid.NewGuid().ToString().Replace("-", string.Empty), cacheExpirate);
                    SetCache(cache, "user_id", cachedUserId ?? dto.UserID, cacheExpirate);

                    result.Items.Add(tokenResponse);
                    result.Success = true;
                }
                else
                {
                    result.AddError(!isValidCredentials ? "Invalid credentials" : "Refresh token is invalid or expired");
                }
            }
            catch (Exception ex)
            {
                result.AddError(ex);
            }

            watch.Stop();

            result.ResponseTime   = watch.Elapsed.TotalSeconds.ToString("0.0### seconds");
            result.HttpStatusCode = System.Net.HttpStatusCode.OK;

            return(result);
        }