public ActionResult <IEnumerable <TokenDTO> > GetToken(LoginDTO loginDto)
        {
            var username = loginDto.username;
            var password = loginDto.password;

            if (CheckUser(username, password))
            {
                var jwtmgr      = new JwtManager(_iconfig);
                var tokenString = jwtmgr.GenerateToken(_user, _user.IsAdmin);
                var tokenDto    = new TokenDTO
                {
                    Token   = tokenString,
                    IsAdmin = _user.IsAdmin,
                    User    = UsersController.UserToDTO(_user)
                };
                HttpContext.Response.Cookies.Append(
                    "auth_cookie",
                    tokenString,
                    new Microsoft.AspNetCore.Http.CookieOptions
                {
                    Expires     = DateTime.Now.AddMinutes(15),
                    HttpOnly    = true,
                    Secure      = true,
                    IsEssential = true
                });
                return(new List <TokenDTO>()
                {
                    tokenDto
                });
            }

            return(Unauthorized());
        }
        private TokenDTO BuildTolken(ApplicationUser user)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Sub, user.Id)
            };

            var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Key-Api-Jwt-My-Taks"));
            var sign = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var exp  = DateTime.UtcNow.AddHours(2);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: exp,
                signingCredentials: sign
                );
            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            var expRefreshToken = DateTime.UtcNow.AddHours(3);

            var refreshToken = Guid.NewGuid().ToString();

            var tokenDTO = new TokenDTO {
                Token = tokenString, expires = exp, ExpirationRefreshToken = expRefreshToken, RefreshToken = refreshToken
            };

            return(tokenDTO);
        }
        public async Task <TokenDTO> Create(ApplicationUser user, IEnumerable <string> roles)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(_JWTSettings.Secret);

            var cliams = new List <Claim>();

            cliams.Add(new Claim(ClaimTypes.Name, user.Id));
            roles.ToList().ForEach(r => cliams.Add(new Claim(ClaimTypes.Role, r)));

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(cliams),
                Expires            = DateTime.Now.AddMinutes(_JWTSettings.MinutesLife),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha256Signature),
            };

            var token        = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
            var refreshToken = _refreshTokenFactory.Create(token, user.UserName);

            await _refreshTokenRepository.Create(refreshToken);

            var tokenDTO = new TokenDTO()
            {
                AccessToken  = token,
                RefreshToken = refreshToken.Token,
                Roles        = roles,
                Email        = user.Email,
                Id           = user.Id
            };

            return(tokenDTO);
        }
Beispiel #4
0
        public TokenDTO Authenticate(AuthDTO authData)
        {
            var validator        = new AuthDataValidator();
            var validationResult = validator.Validate(authData);

            if (!validationResult.IsValid)
            {
                throw new ValidationException(validationResult.Errors);
            }

            var user = _userRepository.GetByEmail(authData.Email);

            if (user == null)
            {
                throw new NotFoundException("Usuário não encontrado ou senha inválida");
            }

            var valid = _cryptoService.VerifyPassword(user.Password, authData.Password);

            if (!valid)
            {
                throw new NotFoundException("Usuário não encontrado ou senha inválida");
            }

            var tokenData = new TokenDTO
            {
                User  = _mapper.Map <User, UserDTO>(user),
                Token = GenerateToken(user)
            };

            return(tokenData);
        }
        public ServiceAccountDTO ConvertToDAO(IAccountSettings serviceAccount)
        {
            ServiceAccountDTO       target         = new ServiceAccountDTO();
            DatabaseAccountSettings currentAccount = (DatabaseAccountSettings)serviceAccount;

            target.ServiceAccountId   = currentAccount.ID;
            target.ServiceAccountName = currentAccount.Name;
            target.Source             = Sources.DataBase;
            target.MinUpdateTime      = target.MinUpdateTime;
            target.AccountVersion     = serviceAccount.AccountVersion;


            List <TokenDTO> tok = new List <TokenDTO>();

            if (currentAccount.Tokens != null)
            {
                foreach (DatabaseAccountToken token in currentAccount.Tokens)
                {
                    TokenDTO localtok = token.ConvertToDAO(token);
                    tok.Add(localtok);
                }
                target.Tokens = tok.ToArray();
            }
            return(target);
        }
        private TokenDTO BuildToken(ApplicationUser usuario)
        {
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Email, usuario.Email),
                new Claim(JwtRegisteredClaimNames.Sub, usuario.Id)
            };

            var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("chave-api-jwt-minhas-tarefas")); //Recomendo -> appsettings.json
            var sign = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var exp  = DateTime.UtcNow.AddHours(1);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: exp,
                signingCredentials: sign
                );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            var refreshToken    = Guid.NewGuid().ToString();
            var expRefreshToken = DateTime.UtcNow.AddHours(2);

            var tokenDTO = new TokenDTO {
                Token = tokenString, Expiration = exp, RefreshToken = refreshToken, ExpirationRefreshToken = expRefreshToken
            };

            return(tokenDTO);
        }
Beispiel #7
0
        public HttpResponseMessage Post(TokenDTO token)
        {
            HttpResponseMessage responseMessage;
            bool valid;

            if (token.Token == null)
            {
                valid = false;
            }
            else
            {
                valid = auth.VerifyTokenDate(token.Token);
                //  valid = true;
            }

            if (!valid)
            {
                // Token invalid
                var json = new JSendMessage("fail", "Invalid Authorization Key");
                responseMessage = Request.CreateResponse(HttpStatusCode.Forbidden, json);
            }
            else
            {
                string role = tokens.GetRoleByToken(token.Token);
                // string role = "admin";
                var json = new RoleMessage(role);
                responseMessage = Request.CreateResponse(HttpStatusCode.OK, json);
            }

            return(responseMessage);
        }
Beispiel #8
0
        /// <summary>
        /// Login del usuario
        /// </summary>
        /// <param name="loginDTO">Datos del login</param>
        /// <param name="config">Archivo de configuración</param>
        /// <param name="ip">IP de la cual se realiza el login</param>
        /// <param name="navegador">Navegador del cual se realiza el login</param>
        /// <returns></returns>
        public async Task <TokenDTO> LoginAsync(LoginDTO loginDTO, IConfiguration config, string ip, string navegador)
        {
            var usuario = await ObtenerPorClave(loginDTO.Usuario);

            if (usuario == null)
            {
                return(tokenDTO);
            }
            if (!EsUsuarioActivo(usuario))
            {
                return(tokenDTO);
            }
            if (!EsPasswordValido(usuario, loginDTO.Password, loginDTO.Codigo))
            {
                return(tokenDTO);
            }
            tokenDTO = GenerarToken(config, usuario.Id, usuario.Nombre);

            UsuarioAccesoDAO usuarioAccesoDAO = new UsuarioAccesoDAO(contexto, localizacion);
            var esOtroNavegador = usuarioAccesoDAO.EsOtroNavegador(navegador, usuario.Id);
            var esOtraCiudad    = await usuarioAccesoDAO.EsOtraCiudadAsync(ip, usuario.Id);

            if (esOtroNavegador || esOtraCiudad)
            {
                EnviaCorreoNuevoAcceso(_path, usuario.Clave, usuario.Email, usuarioAccesoDAO.datosIP, ip, navegador);
            }
            await usuarioAccesoDAO.GuardarAccesoAsync(tokenDTO, usuario.Id, ip, navegador);

            return(tokenDTO);
        }
Beispiel #9
0
        /// <summary>
        /// Genera un token
        /// </summary>
        /// <param name="config">Archivo de configuración</param>
        /// <param name="usuarioId">Id del usuario</param>
        /// <param name="nombre">Nombre del usuario</param>
        /// <returns></returns>
        public TokenDTO GenerarToken(IConfiguration config, int usuarioId, string nombre)
        {
            Token token = new Token(config);

            tokenDTO = new TokenDTO();
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Sid, usuarioId.ToString()),
            };
            RolDAO rolDAO = new RolDAO(contexto, localizacion);
            var    roles  = rolDAO.ObtenerRolesPorUsuarios(usuarioId);

            foreach (var rol in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, rol));
                if (rol == "Vendedor" || rol == "Administrador")
                {
                    var totalCategorias = contexto.UsuarioCategoria
                                          .Where(u => u.UsuarioId == usuarioId).Count();
                    if (totalCategorias > 0)
                    {
                        claims.Add(new Claim("Categorias", totalCategorias.ToString()));
                    }
                }
            }

            DateTime fechaExpiracion = DateTime.Now.AddDays(15).ToLocalTime();

            tokenDTO.Token           = token.GenerarToken(claims.ToArray(), fechaExpiracion);
            tokenDTO.TokenExpiration = fechaExpiracion;
            tokenDTO.UsuarioId       = usuarioId;
            tokenDTO.RefreshToken    = token.RefrescarToken();
            tokenDTO.Nombre          = nombre;
            return(tokenDTO);
        }
        public async Task <TokenDTO> SignInAsync(string phone, string password)
        {
            var user = await database.UserRepository
                       .GetByCondition(u => u.Phone == phone)
                       .SingleOrDefaultAsync();

            if (IsPasswordTheSame(user, password) == false)
            {
                return(null);
            }

            TokenDTO token = jwtFactory.GenerateToken(user.Id, user.Phone, user.Role.Role);

            if (token == null)
            {
                return(null);
            }

            await database.TokenRepository.InsertEntityAsync(
                new Token
            {
                RefreshToken = token.RefreshToken
            }
                );

            bool IsSave = await database.SaveAsync();

            return(IsSave
                ? token
                : null);
        }
        public static void ValidateToken()
        {
            try
            {
                string authenticationToken = HttpContext.Current.Request.Headers["Authentication"];
                if (string.IsNullOrEmpty(authenticationToken))
                {
                    throw new AppException("Usuário não autenticado.", "401");
                }

                // Buscar token e validar:
                TokenDTO token = BookSystem.DataBase.Tokens.Get(authenticationToken);
                if (token == null)
                {
                    throw new AppException("Token não encontrado.", "401");
                }
                if (!token.IsValid)
                {
                    throw new AppException("O token informado não é mais válido.", "401");
                }
                if (DateTime.Now > token.ExpirationDate)
                {
                    throw new AppException("Sua sessão expirou.", "401");
                }

                // Buscar usuário vinculado ao token:
                UserDTO user = User.GetByToken(authenticationToken);
                User.Id    = user.Id;
                User.Name  = user.Name;
                User.Email = user.Email;
            }
            catch (AppException AppEx) { throw AppEx; }
            catch (Exception Ex) { throw Ex; }
        }
Beispiel #12
0
        public void TestPasswordnull()
        {
            AutherService AuthersService = new AutherService(Context, LDAPService.Object, RunningNoService.Object, EncryptionService.Object);
            TokenDTO      ressult        = AuthersService.Login("Test", "");

            Assert.AreEqual("The username or password is incorrect. Please Try again", ressult.Message);
        }
Beispiel #13
0
        public void Testnull()
        {
            AutherService AuthersService = new AutherService(Context, LDAPService.Object, RunningNoService.Object, EncryptionService.Object);
            TokenDTO      result         = AuthersService.Login("", "");

            Assert.AreEqual("Data is null", result.Message);
        }
Beispiel #14
0
        public ActionResult Renovar([FromBody] TokenDTO tokenDTO)
        {
            var refreshtokendb = _tokenrepository.Obter(tokenDTO.RefrashToken);

            if (refreshtokendb == null)
            {
                return(NotFound());
            }
            refreshtokendb.Atualizado = DateTime.Now;
            refreshtokendb.Utilizado  = true;
            _tokenrepository.Atualizar(refreshtokendb);

            //GERAR novo token
            var usuario    = _usuarioRepository.Obter(refreshtokendb.UsuarioId);
            var token      = BuildToken(usuario);
            var tokenModel = new Token()
            {
                RefreshToken           = token.RefrashToken,
                ExpirationToken        = token.Expiration,
                ExpirationRefreshToken = token.ExpirationRefreshToken,
                Usuario   = usuario,
                Criado    = DateTime.Now,
                Utilizado = false
            };

            _tokenrepository.Cadastrar(tokenModel);
            return(Ok(token));
        }
Beispiel #15
0
        public TokenDTO ConvertToDAO(IAccountToken token)
        {
            TokenDTO           target       = new TokenDTO();
            TrelloAccountToken currentToken = (TrelloAccountToken)token;

            target.TokenName = currentToken.TokenName;
            target.TokenId   = currentToken.TokenId;
            List <TokenForSerialization> tokenList = new List <TokenForSerialization>();

            TokenForSerialization userName = new TokenForSerialization();

            userName.Key   = "UserToken";
            userName.Value = currentToken.UserToken;
            tokenList.Add(userName);

            TokenForSerialization dateTime = new TokenForSerialization();

            dateTime.Key   = "DateCreation";
            dateTime.Value = currentToken.DateCreation;
            tokenList.Add(dateTime);

            TokenForSerialization BoardID = new TokenForSerialization();

            BoardID.Key   = "BoardID";
            BoardID.Value = currentToken.BoardID;
            tokenList.Add(BoardID);

            target.Tokens = tokenList.ToArray();
            return(target);
        }
Beispiel #16
0
        /// <summary>
        ///  Function to generate unique token with expiry against the provided userId.
        ///  Also add a record in database for generated token.
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public TokenDTO GenerateToken(int userId)
        {
            string   token    = Guid.NewGuid().ToString();
            DateTime issuedOn = DateTime.Now;

            // TODO set for 24hours?
            DateTime expiredOn   = DateTime.Now.AddSeconds(Convert.ToDouble(ConfigurationManager.AppSettings["AuthTokenExpiry"]));
            var      tokendomain = new Token
            {
                UserId    = userId,
                AuthToken = token,
                IssuedOn  = issuedOn,
                ExpiresOn = expiredOn,
                Request   = 1
            };

            _unitOfWork.TokenRepository.Insert(tokendomain);
            _unitOfWork.Save();
            var tokenModel = new TokenDTO()
            {
                UserId    = userId,
                IssuedOn  = issuedOn,
                ExpiresOn = expiredOn,
                AuthToken = token,
                Request   = 1
            };

            return(tokenModel);
        }
        //public const string BASEURL = @"https://kakprav.com";
        public async Task <bool> LoginAsync(LoginDTO loginDTO)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    var serialized = JsonConvert.SerializeObject(loginDTO);

                    HttpContent httpContent = new StringContent(serialized, Encoding.UTF8, "application/json");
                    var         respnse     = await client.PostAsync(BASEURL + "/api/account/token", httpContent);

                    if (respnse.StatusCode != HttpStatusCode.OK)
                    {
                        return(false);
                    }

                    var stringResult = await respnse.Content.ReadAsStringAsync();

                    AccountInfo = JsonConvert.DeserializeObject <TokenDTO>(stringResult);

                    _storageService.Store(AccountInfo, "token");

                    return(true);
                }
                catch (Exception ex)
                {
                    Mvx.IoCProvider.Resolve <IShortMessagesService>().ShowMessage(ex.Message);
                    return(false);
                }
            }
        }
        public IActionResult Login(Employee user)
        {
            if (!string.IsNullOrWhiteSpace(user.Username) && !string.IsNullOrWhiteSpace(user.Password))
            {
                try
                {
                    //Task<string> returns = AutherService.lo(user.Username,user.Password);
                    //string token = AutherService.Login(user.Username, user.Password);
                    TokenDTO data = AutherService.Login(user.Username, user.Password);

                    if (data.Message == "Login Success")
                    {
                        return(Ok(data));
                    }
                    else
                    {
                        return(BadRequest(data.Message));
                    }
                }
                catch (Exception e)
                {
                    return(BadRequest(e.ToString()));
                }
            }
            else
            {
                return(BadRequest("Username or Password is incorrect. Please Try again!!"));
            }
        }
        public async Task <ActionResult <Candidate> > RedeemToken([FromBody] TokenDTO tokenDTO)
        {
            Candidate candidate = await GetCandidateByToken(tokenDTO.Token);

            if (candidate == null)
            {
                return(NotFound());
            }
            if (candidate.Status == "Completed")
            {
                return(BadRequest("Candidate has completed test."));
            }
            if (candidate.Status == "Examing")
            {
                return(BadRequest("Candidate is currently testing."));
            }

            var TimeEnd = candidate.Test.DateTime().Add(new TimeSpan(0, 40, 0));

            if (DateTime.Now >= TimeEnd)
            {
                return(BadRequest("Test is already over"));
            }

            return(candidate);
        }
        public async Task <TokenDTO> TokenAsync(TokenDTO token)
        {
            try
            {
                var user = await _unitOfWork.UserManager.FindByIdAsync(
                    _jwtFactory.GetPrincipalFromExpiredToken(token.AccessToken).jwt.Subject
                    );

                var role     = (await _unitOfWork.UserManager.GetRolesAsync(user)).SingleOrDefault();
                var newToken = _jwtFactory.GenerateToken(user.Id, user.UserName, role);

                return(newToken);
            }
            catch (Exception e)
                when(e is SecurityTokenException || e is DbUpdateException)
                {
                    _logger.LogError(e, nameof(TokenAsync));
                    return(null);
                }
            catch (Exception e)
            {
                _logger.LogError(e, nameof(TokenAsync));
                throw;
            }
        }
        public async Task <int> CreateAsync <TSource, TDestination>(TSource item)
            where TSource : class
            where TDestination : class
        {
            _token = await _jwtTokenService.CheckTokenAsync(_token);

            var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client  = new Courses.CoursesClient(channel);

            var headers = new Metadata();

            headers.Add("Authorization", $"Bearer {_token.Token}");

            var reply = await client.CreateCourseAsync(
                new CourseMessage { Title = "BestTitle" }, headers);

            /*  var channel = await CreateAuthenticatedChannel("https://localhost:5001");
             * var client = new CoursesService.CoursesServiceClient(channel);
             */
            /* var serviceFactory = _grpcServiceFactory.GetService<TSource>();
             * serviceFactory
             *
             * var reply = await client.CreateCourseAsync(
             *  new CourseMessage { Title = "BestTitle" });.*/

            return(reply.Id);
        }
Beispiel #22
0
        public string GenerateToken(TokenDTO tokenDTO)
        {
            int    tokenExpiery = int.Parse(config["AccessTokenLife"]);
            Header header       = new Header
            {
                alg = algorithm,
                typ = config.GetValue <string>("jwt:header:typ")
            };

            Payload payload = new Payload
            {
                iss      = config.GetValue <string>("jwt:payload:iss"),
                sub      = tokenDTO.UserName,
                exp      = new TimeSpan(0, 0, tokenExpiery, 0, 0).TotalSeconds.ToString(),
                iat      = DateTime.Now.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                nbf      = DateTime.Now.AddMinutes(tokenExpiery).ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"),
                jti      = Guid.NewGuid().ToString(),
                username = tokenDTO.UserName,
                admin    = true
            };

            string headerStr    = JsonSerializer.Serialize(header);
            string payloadStr   = JsonSerializer.Serialize(payload);
            string signatureStr = GetSignature(headerStr, payloadStr, SecretKey, (ALG)Enum.Parse(typeof(ALG), algorithm, true));
            string tokenStr     = headerStr.Base64Encode() + "." + payloadStr.Base64Encode() + "." + signatureStr;

            return(tokenStr);
        }
        public async Task InvokeAsync(HttpContext context, ITokenLogic _tokenLogic)
        {
            string value = context.Request.Cookies["AuthenticationToken"];

            if (!string.IsNullOrEmpty(value))
            {
                TokenDTO tokenDTO = _tokenLogic.GetTokenByValue(value);
                if (tokenDTO == null)
                {
                    RemoveTokenFromCookie(context, value);
                    await _next(context);

                    return;
                }
                if (DateTime.Compare(tokenDTO.ExpirationDate, DateTime.Now) < 0)
                {
                    RemoveTokenFromCookie(context, value);
                    RemoveTokenFromDb(_tokenLogic, tokenDTO.TokenId);
                    await _next(context);

                    return;
                }
            }
            // Call the next delegate/middleware in the pipeline
            await _next(context);

            return;
        }
        public async Task <TokenDTO> GetToken(AuthParam login)
        {
            var user = new UsuarioEntity
            {
                Login = login.Login,
                Senha = login.Senha
            };
            var retorno = new TokenDTO
            {
                Authenticated  = false,
                CreationDate   = null,
                ExpirationDate = null,
                Message        = "Authentication Failure."
            };
            var retornoRepo = await _usuariosRepository.GetUsuarioByLoginSenha(user);

            if (retornoRepo != null)
            {
                retorno.Authenticated  = true;
                retorno.AccessToken    = GerarJwt(retornoRepo);
                retorno.CreationDate   = DateTime.Now;
                retorno.ExpirationDate = DateTime.Now.AddHours(Convert.ToInt32(_appSettings.ExpirationHours));
                retorno.Message        = "OK";
            }

            return(retorno);
        }
Beispiel #25
0
        public static TokenDTO Get(string tokenguid)
        {
            TokenDTO      token      = null;
            SqlConnection ConnectSQL = new SqlConnection(_DataBase.ConnectionString);
            string        SQL        = Querys.Tokens.Get;

            try
            {
                SqlCommand sqlCommand = new SqlCommand(SQL, ConnectSQL);
                sqlCommand.CommandType = System.Data.CommandType.Text;
                ConnectSQL.Open();
                sqlCommand.Parameters.Add(new SqlParameter("@Token", tokenguid));

                SqlDataReader readDataBase = sqlCommand.ExecuteReader();
                while (readDataBase.Read())
                {
                    token                = new TokenDTO();
                    token.Token          = tokenguid;
                    token.UserId         = Convert.ToInt32(readDataBase["UserID"].ToString());
                    token.IsValid        = bool.Parse(readDataBase["Active"].ToString());
                    token.ExpirationDate = DateTime.Parse(readDataBase["ExpirationDate"].ToString());
                }
                return(token);
            }
            catch (SqlException sqlEx) { throw sqlEx; }
            finally { ConnectSQL.Close(); }
        }
Beispiel #26
0
        public AuthenticationDTO AuthenticateGetToken(TokenDTO tokenDTO)
        {
            string          _refreshTokenold = HttpUtility.UrlDecode(tokenDTO.Refresh_Token);
            string          _refreshToken    = refreshtoken.GenerateToken(tokenDTO);
            RefreshTokenDTO refauth          = new RefreshTokenDTO {
                Authorization = _refreshTokenold
            };
            AuthenticationDTO auth = new AuthenticationDTO();

            try
            {
                //  ValidationResult results = refreshvalidation.Validate(refauth);
                Authorize authorize = oauth.Authorize.Where(x => x.Code == refauth.Authorization).FirstOrDefault();
                User      user      = oauth.User.SingleOrDefault(x => x.UserId == authorize.UserId);
                UserDTO   userDTO   = mapper.Map <UserDTO>(user);
                auth.token_type    = config["TokenType"];
                auth.access_token  = JWTToken.GenerateToken(tokenDTO);
                auth.refresh_token = HttpUtility.UrlEncode(_refreshToken);
                authorize.Code     = _refreshToken;
                oauth.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Log.Error(ex, TokenConstants.InvalidUser);
                throw new InvalidUserException(TokenConstants.InvalidUser);
            }
            return(auth);
        }
Beispiel #27
0
        public async Task <ActionResult <TokenResponse> > GetToken([FromBody] TokenDTO value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // async request - await para aguardar retorno
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

            // nesta parte, temos um exemplo de requisição com o tipo "password"
            // esta é a forma mais comum
            var httpClient    = new HttpClient();
            var tokenResponse = await httpClient.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = disco.TokenEndpoint,
                ClientId     = "codenation.api_client",
                ClientSecret = "codenation.api_secret",
                UserName     = value.UserName,
                Password     = value.Password,
                Scope        = "codenation"
            });

            // Se não tiver tiver um erro retornar token
            if (!tokenResponse.IsError)
            {
                return(Ok(tokenResponse));
            }

            //retorna não autorizado e descrição do erro
            return(Unauthorized(tokenResponse.ErrorDescription));
        }
Beispiel #28
0
        public async Task <TokenResponse> GetTokenAsync(TokenDTO model)
        {
            var authenticationModel = new TokenResponse();
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                authenticationModel.Message = $"No Accounts Registered with {model.UserName}.";
                return(authenticationModel);
            }
            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                authenticationModel.Token = await CreateJwtToken(user);

                authenticationModel.Email    = user.Email;
                authenticationModel.UserName = user.UserName;
                var rolesList = await _userManager.GetRolesAsync(user).ConfigureAwait(false);

                authenticationModel.Role      = rolesList.ToList().FirstOrDefault();
                authenticationModel.LibraryId = user.LibraryId;

                var refreshToken = GenerateRefreshToken();
                user.RefreshToken = refreshToken;
                user.RefreshTokenExpirationDate  = DateTime.Now.AddDays(7);
                authenticationModel.RefreshToken = refreshToken;
                await _userManager.UpdateAsync(user);

                return(authenticationModel);
            }
            authenticationModel.Message = $"Incorrect Credentials.";
            return(authenticationModel);
        }
        private async Task <TokenDTO> GenerateJwtToken(string email, MODUser user)
        {
            var roles = await userManager.GetRolesAsync(user);

            var role = roleManager.Roles.SingleOrDefault(r => r.Name == roles.SingleOrDefault());

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Role, role.Name)
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            // recommended is 5 min
            var expires = DateTime.Now.AddDays(Convert.ToDouble(configuration["JwtExpireDays"]));
            var token   = new JwtSecurityToken(
                configuration["JwtIssuer"],
                configuration["JwtIssuer"],
                claims,
                expires: expires,
                signingCredentials: creds
                );

            var response = new TokenDTO
            {
                Email = email,
                Role  = Convert.ToInt32(role.Id),
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            };

            return(response);
        }
Beispiel #30
0
        public static bool ValidToken(string token)
        {
            try
            {
                TokenDTO tokenInfo   = GetTokenInfo(token);
                Mc_Token tokenEntity = DBUtility.CubeDb.From <Mc_Token>().Where(Mc_Token._.Secret_Key == tokenInfo.SecretKey).Select(Mc_Token._.All).ToList().FirstOrDefault();
                if (tokenEntity == null)
                {
                    return(false);
                }

                Mc_User userEntity = DBUtility.CubeDb.From <Mc_User>().Where(Mc_User._.Id == tokenEntity.User_Id).FirstDefault();
                if (userEntity == null)
                {
                    return(false);
                }

                if (!tokenInfo.LoginName.Equals(userEntity.Login_Name, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(false);
                }

                TimeSpan span = DateTime.Now - tokenInfo.LoginTime;
                if (span.TotalMinutes > TokenOverdueMiniute)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
        public IAccountToken ConvertFromDAO(TokenDTO token)
        {
            TrelloAccountToken targetToken = new TrelloAccountToken();
            targetToken.TokenId = token.TokenId;
            targetToken.TokenName = token.TokenName;
            if (token.Tokens.Length > 0)
            {
                targetToken.UserToken = (from tok in token.Tokens
                                         where tok.Key == "UserToken"
                                         select tok.Value).SingleOrDefault();

                targetToken.DateCreation = (from tok in token.Tokens
                                         where tok.Key == "DateCreation"
                                         select tok.Value).SingleOrDefault();
                targetToken.BoardID = (from tok in token.Tokens
                                            where tok.Key == "BoardID"
                                            select tok.Value).SingleOrDefault();
            }
            return targetToken;
        }
        public TokenDTO ConvertToDAO(IAccountToken token)
        {
            TokenDTO target = new TokenDTO();
            TrelloAccountToken currentToken = (TrelloAccountToken)token;

            target.TokenName = currentToken.TokenName;
            target.TokenId = currentToken.TokenId;
            List<TokenForSerialization> tokenList = new List<TokenForSerialization>();

            TokenForSerialization userName = new TokenForSerialization();
            userName.Key = "UserToken";
            userName.Value = currentToken.UserToken;
            tokenList.Add(userName);

            TokenForSerialization dateTime = new TokenForSerialization();
            dateTime.Key = "DateCreation";
            dateTime.Value = currentToken.DateCreation;
            tokenList.Add(dateTime);

            TokenForSerialization BoardID = new TokenForSerialization();
            BoardID.Key = "BoardID";
            BoardID.Value = currentToken.BoardID;
            tokenList.Add(BoardID);

            target.Tokens = tokenList.ToArray();
            return target;
        }
 private static List<DelegationDTO> GetDelegations(TokenDTO tokenDTO)
 {
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
     AAServiceV2Client aaServiceClient = new AAServiceV2Client();
     return aaServiceClient.GetDelegations(tokenDTO, AuthorizationInfoDTO.User.UserID, AuthorizationInfoDTO.ApplicationCode).ToList();
 }
        public static AuthorizationInfoDTO GetAuthorizationDataFromToken(string tokenString)
        {
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
            AAServiceV2Client aaServiceClient = new AAServiceV2Client();

            TokenDTO token = new TokenDTO();
            token.TokenString = tokenString;
            AuthorizationInfoDTO _authorizationInfoDTO = aaServiceClient.IsAuthenticated(token, APPLICATION);

            foreach (RoleDTO roleDTO in _authorizationInfoDTO.Roles)
            {
                roleDTO.ApplicationContexts = roleDTO.ApplicationContexts.Where(item => item.ApplicationContext1 == CONTEXT_ONE || item.ApplicationContext1 == "*").ToList();
            }
            _authorizationInfoDTO.Roles = _authorizationInfoDTO.Roles.Where(item => item.ApplicationContexts.Count > 0).ToList();

            foreach (ScenarioDTO scenarioDTO in _authorizationInfoDTO.Scenarios)
            {
                scenarioDTO.ApplicationContexts = scenarioDTO.ApplicationContexts.Where(item => item.ApplicationContext1 == CONTEXT_ONE || item.ApplicationContext1 == "*").ToList();
            }
            _authorizationInfoDTO.Scenarios = _authorizationInfoDTO.Scenarios.Where(item => item.ApplicationContexts.Count > 0).ToList();

            return _authorizationInfoDTO;
        }
 private static List<RoleDTO> GetRolesOfUser(TokenDTO tokenDTO, int userID)
 {
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
     AAServiceV2Client aaServiceClient = new AAServiceV2Client();
     List<RoleDTO> roles = aaServiceClient.GetRolesOfUser(tokenDTO, userID, APPLICATION);
     roles = roles.Where(item => item.ApplicationContexts.Any(q => (q.ApplicationContext1 == "*" || q.ApplicationContext1 == CONTEXT_ONE) &&
                                                                   (q.ApplicationContext2 == "*" || q.ApplicationContext2 == CONTEXT_TWO))).ToList();
     return roles;
 }
 private static SignatureDTO GetSignature(TokenDTO tokenDTO, int userID)
 {
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
     AAServiceV2Client aaServiceClient = new AAServiceV2Client();
     return aaServiceClient.GetSignature(tokenDTO, userID, APPLICATION);
 }
 private static List<UserDTO> GetUsersInRole(TokenDTO tokenDTO, string role, bool onlyActives, bool includingDelegations)
 {
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
     AAServiceV2Client aaServiceClient = new AAServiceV2Client();
     return aaServiceClient.GetUsersInRole(tokenDTO, role, APPLICATION, CONTEXT_ONE, CONTEXT_TWO, onlyActives, includingDelegations, false);
 }
 private static List<RoleDTO> GetActiveRoles(TokenDTO tokenDTO)
 {
     ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
     AAServiceV2Client aaServiceClient = new AAServiceV2Client();
     return aaServiceClient.GetActiveRoles(tokenDTO, APPLICATION);
 }
        public IAccountToken ConvertFromDAO(TokenDTO token)
        {
            GoogleSheetsAccountToken targetToken = new GoogleSheetsAccountToken();
            targetToken.TokenId = token.TokenId;
            targetToken.TokenName = token.TokenName;
            if (token.Tokens.Length > 0)
            {
                targetToken.RefreshToken = (from tok in token.Tokens
                                            where tok.Key == "RefreshToken"
                                            select tok.Value).SingleOrDefault();
            }

            return targetToken;
        }
        public TokenDTO ConvertToDAO(IAccountToken token)
        {
            TokenDTO target = new TokenDTO();
            GoogleSheetsAccountToken currentToken = (GoogleSheetsAccountToken)token;

            target.TokenName = currentToken.TokenName;
            target.TokenId = currentToken.TokenId;
            List<TokenForSerialization> tokenList = new List<TokenForSerialization>();

            TokenForSerialization password = new TokenForSerialization();
            password.Key = "RefreshToken";
            password.Value = currentToken.RefreshToken;
            tokenList.Add(password);

            target.Tokens = tokenList.ToArray();
            return target;
        }
        public Boolean DeleteToken(TokenDTO token)
        {
            Boolean succeed = false;
            ISessionFactory sessionFactory = NhibernateSessionFactory.GetSessionFactory(NhibernateSessionFactory.SessionFactoryConfiguration.Application);
            TokenDAO target = token.TokenDTOToTokenDomain().TokenToTokenDAO();
            using (ISession session = sessionFactory.OpenSession())
            {
                ServiceAccountDAO account = session.Query<ServiceAccountDAO>().Where(acount => acount.Tokens.Contains(target)).SingleOrDefault();
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(target);
                    transaction.Commit();
                    succeed = transaction.WasCommitted;
                }
                if (succeed)
                {
                    UpdateAccountVersion(account.ServiceAccountId, account.AccountVersion + 1);
                }

            }
            return succeed;
        }
        public static TokenDTO TokenToTokenDTO(this Token param)
        {
            TokenDTO target = new TokenDTO();

            target.TokenId = param.TokenId;
            target.TokenName = param.TokenName;
            foreach (KeyValuePair<string, string> item in param.Tokens)
            {
                target.Tokens.Add(new TokenForSerialization { Key = item.Key, Value = item.Value });
            }

            return target;
        }