public TokenJWT validarTokenJWT(TokenJWT token)
        {
            TokenJWT respuesta = new TokenJWT();

            try
            {
                /*
                 * Aplicacion aplicacion = (Aplicacion)_ufw.RepositoryBaseCommand<Aplicacion>().Find(new AplicacionSpecification(token.IdAplicacion, true, true));
                 *
                 * respuesta.IdAplicacion = token.IdAplicacion;
                 * respuesta.TokenValido = false;
                 * respuesta.Token = token.Token;
                 *
                 * if (aplicacion != null)
                 * {
                 *  respuesta.TokenValido = TokenValidator.ValidarTokenJWT(token.Token, aplicacion.LlaveSecreta, this.Issuer, aplicacion.IdAplicacion, TimeSpan.Zero);
                 * }
                 *
                 * respuesta.Token = (respuesta.TokenValido) ? "Token Válido" : "Token Inválido";
                 */
            }
            catch (Exception e)
            {
                throw e;
            }

            return(respuesta);
        }
Beispiel #2
0
        public ServiceResult <bool> PostChangePassword(int id, [FromBody] Passwords password)
        {
            ServiceResult <bool> result = null;

            if (password != null)
            {
                try
                {
                    result = this.appService.ChangePassword(TokenJWT.GetUserByToken(Request.Headers["Authorization"]), password.Password);
                }
                catch (Exception ex)
                {
                    result         = new ServiceResult <bool>();
                    result.Errors  = new string[] { ex.Message };
                    result.Success = false;
                }
            }
            else
            {
                result        = new ServiceResult <bool>();
                result.Errors = new string[1] {
                    MessageValidator.PasswordRequired
                };
                result.Success = false;
            }

            return(result);
        }
        public LoginResponse Post([FromBody] LoginRequest cuenta)
        {
            LoginResponse response = new LoginResponse();

            response.Autenticacion = false;
            response.Bloqueado     = false;

            if (!cuenta.datosParaLogin())
            {
                Response.StatusCode = 202;
                response.Mensaje    = "Solicitud Inválida";
                return(response);
            }
            TokenJWT token = null;

            try
            {
                token = negocio.iniciarSesion(cuenta).Result;
                Response.StatusCode = 201;
            }
            catch (Exception e)
            {
                Response.StatusCode = 203;
                response.Mensaje    = e.Message;
                return(response);
            }

            if (token == null)
            {
                Response.StatusCode = 203;
                response.Mensaje    = "Inicio de Sesión Inválido";
                return(response);
            }

            //if (String.IsNullOrEmpty(token.Abreviacion))
            //{
            //    Response.StatusCode = 202;
            //    response.Mensaje = token.Token;
            //    return response;
            //}

            //LDAP Account Locked
            if (String.IsNullOrEmpty(token.Token))
            {
                Response.StatusCode = 203;
                response.Bloqueado  = true;
                response.Mensaje    = "Cuenta bloqueada.";
                return(response);
            }

            response.Autenticacion = true;
            response.TokenJWT      = token.Token;
            response.Mensaje       = "Sesión Iniciada";

            return(response);
        }
        public TokenJWT renovarToken(TokenJWT token)
        {
            TokenJWT newToken = null;

            if (validarTokenJWT(token))
            {
                newToken             = new TokenJWT();
                newToken.Token       = TokenGenerator.renovarTokenJWT(token.Token, this.SecretKey, this.lifeMinutes, this.Issuer, this.Audience, dbManager);
                newToken.TokenValido = true;
            }
            return(newToken);
        }
        public TokenJWT renovarToken(TokenJWT token)
        {
            TokenJWT newToken = null;

            /*
             * if (validarTokenJWT(token).TokenValido)
             * {
             *  Aplicacion app = (Aplicacion)_ufw.RepositoryBaseCommand<Aplicacion>().Find(new AplicacionSpecification(token.IdAplicacion));
             *  newToken = new TokenJWT();
             *  newToken.IdAplicacion = app.IdAplicacion;
             *  newToken.Token = TokenGenerator.renovarTokenJWT(token.Token, app.LlaveSecreta, app.MinutosDeVida.Value, this.Issuer, app.IdAplicacion);
             *  newToken.TokenValido = true;
             * }
             */
            return(newToken);
        }
Beispiel #6
0
        public async Task <GetTokenResultDto> GetToken(string adminName, string adminPwd)
        {
            string jwtStr = string.Empty;

            // 判断是否为空
            if (string.IsNullOrEmpty(adminName) || string.IsNullOrEmpty(adminPwd))
            {
                // 账号或密码不能为空
                throw new Exception("Account or password cannot be empty.");
            }

            var result = await HttpRequestService.HttpGetAsync(AppConfigurtaionService.Configuration["ProjectInfo:ApiUrl"]
                                                               + string.Format("/api/Admin/IsExistFromToken?adminName={0}&adminPwd={1}", adminName, adminPwd));

            //StringBuilder resultStringBuilder = new StringBuilder();

            // 去除转义字符
            //foreach (char c in result.ToString())
            //{
            //    if (c != '\\') resultStringBuilder.Append(c);
            //}
            // 返回字符串转换为JSON对象
            var admin = JsonConvert.DeserializeObject <Model.Entity.Admin>(result);

            TokenJWT tokenModel = new TokenJWT();

            tokenModel.Id        = admin.Id;
            tokenModel.AdminName = admin.AdminName;

            jwtStr = JWTService.IssueJWT(tokenModel);

            return(new GetTokenResultDto()
            {
                JWT = "Bearer " + jwtStr,
            });
        }
Beispiel #7
0
 public CurrentUser(Usuario usuario, TokenJWT token)
 {
     this.Usuario = usuario;
     this.Token   = token.value;
 }
 public TokenJWT cambiarContrasena(TokenJWT token)
 {
     throw new NotImplementedException();
 }
Beispiel #9
0
        private string GenerateTokenJWT(string Id, string Email)
        {
            TokenJWT jwt = new TokenJWT();

            return(jwt.GetToken(Id, Email));
        }
        public async Task <TokenJWT> iniciarSesion(LoginRequest account)
        {
            TokenJWT     token  = null;
            SignInResult result = SignInResult.Failed;

            try
            {
                string user = account.Usuario;
                user = user.Contains("@") ? user.Split("@")[0] : user;

                Usuario    appUser = signInManager.UserManager.FindByNameAsync(user).Result;
                List <Rol> roles   = dbManager.Roles.ToList();

                if (appUser != null)
                {
                    account.Usuario = account.Usuario.Contains("@") ? account.Usuario.Split("@")[0] : account.Usuario;


                    bool hasRole = false;

                    foreach (Rol rol in roles)
                    {
                        if (signInManager.UserManager.IsInRoleAsync(appUser, rol.Name).Result)
                        {
                            hasRole = true;
                            continue;
                        }
                    }

                    if (!hasRole)
                    {
                        throw new Exception("El usuario no tiene permisos para iniciar sesión.");
                    }



                    //Account Service

                    user = user.Contains("@") ? user.Split("@")[0] : user;

                    SignInResult validation = signInManager.PasswordSignInAsync(appUser, account.Contrasena, false, false).Result;

                    if (validation.Succeeded)
                    {
                        result = SignInResult.Success;
                    }
                }

                if (result.Succeeded)
                {
                    IList <string> rolesUsuario = signInManager.UserManager.GetRolesAsync(appUser).Result;
                    List <Claim>   claimsJWT    = new List <Claim>();

                    foreach (Rol rol in roles)
                    {
                        if (rolesUsuario.Contains(rol.Name))
                        {
                            claimsJWT.Add(new Claim(ClaimTypes.Role, rol.Name));
                        }
                    }
                    claimsJWT.Add(new Claim(ClaimTypes.NameIdentifier, appUser.UserName));
                    claimsJWT.Add(new Claim(ClaimTypes.Email, appUser.Email));
                    claimsJWT.Add(new Claim(ClaimTypes.GivenName, appUser.FirstName + " " + appUser.LastName));



                    string jwt = TokenGenerator.GenerateTokenJWT(this.SecretKey, this.Algorithm, claimsJWT, this.lifeMinutes, this.Issuer, this.Audience, dbManager);

                    token       = new TokenJWT();
                    token.Token = jwt;
                }
                else
                {
                    if (token == null)
                    {
                        token       = new TokenJWT();
                        token.Token = "La dupla Usuario/Contraseña es incorrecta.";
                    }
                    else
                    {
                        token       = new TokenJWT();
                        token.Token = "Usuario incorrecto";
                    }
                }
            }
            catch (Exception e)
            {
                token       = new TokenJWT();
                token.Token = e.Message;
            }
            return(token);
        }
 public bool validarTokenJWT(TokenJWT token)
 {
     return(TokenValidator.ValidarTokenJWT(token.Token, this.SecretKey, this.Issuer, this.Audience, TimeSpan.Zero, dbManager));
 }