Exemple #1
0
            public static ResponseAuth GenerateToken(AuthRequest model, int expireMinutes = 120)
            {
                var symmetricKey = Convert.FromBase64String(Secret);
                var tokenHandler = new JwtSecurityTokenHandler();

                var          now    = DateTime.UtcNow;
                List <Claim> claims = new List <Claim> {
                    new Claim(ClaimTypes.Name, model.Username)
                };

                var user = new AuthUser();

                var userModel = user.GetUser(model.Username);

                foreach (var role in userModel.UserRoles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(claims),

                    Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),

                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature)
                };

                var stoken = tokenHandler.CreateToken(tokenDescriptor);
                var token  = tokenHandler.WriteToken(stoken);

                return(new ResponseAuth(ResultEnum.AuthUser, token, tokenDescriptor.Expires.Value));
            }
        public IHttpActionResult Post([FromBody] AuthRequest authModel)
        {
            var user = new AuthUser();

            if (user.GetUser(authModel.Username, authModel.Password) == null)
            {
                return(Unauthorized());
            }


            return(Ok(JwtManager.GenerateToken(authModel)));
        }
        private static bool ValidateToken(string token, string roles, out string username, out List <string> userRoles)
        {
            username  = null;
            userRoles = null;
            var contextRoles    = roles.Split(',');
            var simplePrinciple = JwtManager.GetPrincipal(token);
            var identity        = simplePrinciple?.Identity as ClaimsIdentity;

            if (identity == null)
            {
                return(false);
            }

            if (!identity.IsAuthenticated)
            {
                return(false);
            }

            var usernameClaim = identity.FindFirst(ClaimTypes.Name);

            username = usernameClaim?.Value;

            if (string.IsNullOrEmpty(username))
            {
                return(false);
            }

            var user      = new AuthUser();
            var userModel = user.GetUser(usernameClaim.Value);

            if (userModel == null)
            {
                return(false);
            }

            if (!userModel.UserRoles.Any(contextRoles.Contains))
            {
                return(false);
            }

            userRoles = userModel.UserRoles;

            return(true);
        }