コード例 #1
0
        public ResponsePackage <UsuarioDto> Authenticate(string email, string clave)
        {
            var responsePackage = new ResponsePackage <UsuarioDto>();
            var user            = _db.Usuario.SingleOrDefault(x => x.Email == email && x.Clave == clave);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token   = tokenHandler.CreateToken(tokenDescriptor);
            var usuario = new UsuarioDto
            {
                Id              = user.Id.ToString(),
                Nombre          = user.Nombre,
                Apellido        = user.Apellido,
                Email           = user.Email,
                Clave           = user.Clave,
                TipoDocumentoId = user.TipoDocumentoId.ToString(),
                NumeroDocumento = user.NumeroDocumento,
                RolId           = user.RolId.ToString()
            };
            var Role = _db.Rol.FirstOrDefault(r => r.Id == user.RolId);

            usuario.RolId = Role.Nombre;
            usuario.Token = tokenHandler.WriteToken(token);

            responsePackage.Message = "";
            responsePackage.Result  = usuario.WithoutPassword();
            return(responsePackage);
        }