コード例 #1
0
        private bool ValidateToken(string token, out IPrincipal simplePrinciple)
        {
            string username = null;
            string role     = null;

            simplePrinciple = JwtTokenLibrary.GetPrincipal(token);
            if (simplePrinciple == null)
            {
                return(false);
            }

            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 roleClaim = identity.FindFirst(ClaimTypes.Role);

            role = roleClaim?.Value;

            if (string.IsNullOrEmpty(role) && role.ToLower() != "admin" && role.ToLower() != "teacher" && role.ToLower() != "student")
            {
                return(false);
            }

            return(true);
        }
コード例 #2
0
        public string GetToken()
        {
            string username = HttpContext.Current.Request.Headers["username"];
            string password = HttpContext.Current.Request.Headers["password"];

            if (username == null || password == null)
            {
                throw new Exception("Unauthorized");
            }

            BusinessContext context = new BusinessContext();
            User            user    = context.UserBusiness.ReadUser(username, password);

            if (user == null)
            {
                throw new Exception("Unauthorized");
            }

            return(JwtTokenLibrary.GenerateToken(username, user.Role.ToString(), RsaEncryption.Encryption(password)));
        }