Пример #1
0
        public static bool Verify <TToken, TJwtHeader, TJwtPayload>(
            string token,
            TokenValidationParameters validationParameters,
            out TToken result)
            where TToken : class, IJwtToken <TJwtHeader, TJwtPayload>
            where TJwtHeader : IJwtHeader
        {
            result = default(TToken);

            try {
                var nToken = new JWT.JwtSecurityToken(token.Split(' ').Last());

                var header  = (TJwtHeader)DictionaryToJObject(nToken.Header).ToObject(typeof(TJwtHeader));
                var payload = (TJwtPayload)DictionaryToJObject(nToken.Payload).ToObject(typeof(TJwtPayload));

                result         = (TToken)FormatterServices.GetUninitializedObject(typeof(TToken));
                result.Header  = header;
                result.Payload = payload;

                if (validationParameters == null)   //不走驗證
                {
                    return(true);
                }

                var tokenHandler = new JwtSecurityTokenHandler();

                tokenHandler.ValidateToken(token.Split(' ').Last(), validationParameters, out _);

                return(true);
            } catch {
                return(false);
            }
        }
Пример #2
0
    public ClaimsPrincipal GetPrincipal()
 {
     try
     {
         //String jwt = ((String)this.Request.Headers["Authorization"]). Replace("Bearer ", string.Empty);
         String authHeader = Request.Headers["Authorization"];
         authHeader = authHeader.Replace("Bearer ", "");
         var tokenHandler = new JwtSecurityTokenHandler();
         var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(authHeader);                
         if (token == null)
             return null;     
         var validationParameters = new TokenValidationParameters()
         {
            RequireExpirationTime = true,
            ValidateIssuer = false,
            ValidateAudience = false,
            IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey()
         };
         SecurityToken securityToken;            
         var principal = tokenHandler.ValidateToken(authHeader, validationParameters, out securityToken);
         if(securityToken.ValidTo < DateTime.UtcNow)
         {return null;}
         return principal;
     }
     catch (Exception)
     {            
         return null;
     }
 }
Пример #3
0
        public async Task <string> GenerateEncodedToken(string userName, ClaimsIdentity identity)
        {
            try
            {
                var claims = new[]
                {
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Sub, userName),
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Jti, await jwtOptions.JtiGenerator()),
                    new Claim(Microsoft.IdentityModel.JsonWebTokens.JwtRegisteredClaimNames.Iat, ToUnixEpochDate(jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
                    identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol),
                    identity.FindFirst(Helpers.Constants.Strings.JwtClaimIdentifiers.Id)
                };

                // Create the JWT security token and encode it.
                var jwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                    issuer: jwtOptions.Issuer,
                    audience: jwtOptions.Audience,
                    claims: claims,
                    notBefore: jwtOptions.NotBefore,
                    expires: jwtOptions.Expiration,
                    signingCredentials: jwtOptions.SigningCredentials);

                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                return(encodedJwt);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #4
0
        private string BuildToken(Users user)
        {
            // key is case-sensitive
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, Configuration["Jwt:Subject"]),
                new Claim("id", user.Id.ToString()),
                new Claim("username", user.Username),
                new Claim("position", user.Position),
                new Claim(ClaimTypes.Role, user.Position)
            };

            var expires = DateTime.Now.AddDays(Convert.ToDouble(Configuration["Jwt:ExpireDay"]));

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                issuer: Configuration["Jwt:Issuer"],
                audience: Configuration["Jwt:Audience"],
                claims: claims,
                expires: expires,
                signingCredentials: creds
                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #5
0
        async public Task <string> BuildJwtAuthorizationToken(User user, TokenProviderOptions options)
        {
            var now = DateTime.UtcNow;
            // Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims.
            // You can add other claims here, if you want:
            var claims = new List <Claim>()
            {
                new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub, user.Id),
                new Claim(ClaimTypes.Name, user.Id),
                new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Jti, await options.NonceGenerator()),
                //new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64)
            };

            foreach (Rol role in user.Roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role.value));
            }

            var jwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                issuer: options.Issuer,
                claims: claims,
                notBefore: now,
                signingCredentials: options.SigningCredentials);
            var encodedJwt = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
Пример #6
0
 public UsersDTO(Users user, System.IdentityModel.Tokens.Jwt.JwtSecurityToken token)
 {
     Id        = user.Id;
     Login     = user.Login;
     Email     = user.Email;
     Token     = token;
     Role_Name = user.Role;
 }
Пример #7
0
        protected TokenData GetTokenData()
        {
            var tok = Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);

            var handler = new JwtSecurityTokenHandler();
            //var tokenS = handler.ReadToken(headerValue.Parameter) as JwtSecurityToken;
            var tokenS = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(tok);

            var email = tokenS.Claims.First(claim => claim.Type == JwtRegisteredClaimNames.Email).Value;
            var id    = tokenS.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.UniqueName).Value;

            return(new TokenData(email, new Guid(id)));
        }
Пример #8
0
        /// <summary>
        /// 簽名並產生JWT字串
        /// </summary>
        /// <typeparam name="TJwtHeader">標頭類型</typeparam>
        /// <typeparam name="TJwtPayload">內容類型</typeparam>
        /// <param name="token">JWT結構</param>
        /// <param name="signingCredentials">簽名鑰匙</param>
        /// <returns>JWT字串</returns>
        public static string Sign <TJwtHeader, TJwtPayload>(
            this IJwtToken <TJwtHeader, TJwtPayload> token,
            SecurityKey signingCredentials)
            where TJwtHeader : IJwtHeader
        {
            var nToken = new SystemJWT.JwtSecurityToken(signingCredentials: new SigningCredentials(signingCredentials, token.Header.Algorithm));

            SetToJwtHeader(token.Header, nToken.Header);
            SetToJwtPayload(token.Payload, nToken.Payload);

            return("bearer " + new SystemJWT.JwtSecurityTokenHandler().WriteToken(
                       nToken
                       ));
        }
Пример #9
0
        private string GenerateJSONWebToken(User userInfo)
        {
            _log4net.Info("Token Generation initiated");
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_config["Jwt:Issuer"],
                                                                             _config["Jwt:Issuer"],
                                                                             null,
                                                                             expires: DateTime.Now.AddMinutes(30),
                                                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        //Tạo AccessToken
        private string GenerateToken(ThanhVienDangNhapViewModel thanhVienDNVM)
        {
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                claims: new Claim[] {
                new Claim(ClaimTypes.Name, thanhVienDNVM.TaiKhoan),
                new Claim(ClaimTypes.Role, thanhVienDNVM.MaLoaiThanhVien.ToString()),
            },
                notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
                signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)

                );

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #11
0
        public string GenerateJWTToken(string name)
        {
            var JwtToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_config.issuer,
                                                                                _config.audience,
                                                                                new[] {
                new Claim(ClaimTypes.Name, name)
            },
                                                                                null,
                                                                                DateTime.Now.AddMinutes(5),
                                                                                new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config.secret)),
                                                                                                                                      Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature));

            var accessToken = new JwtSecurityTokenHandler().WriteToken(JwtToken);

            return(accessToken);
        }
        public async Task <IActionResult> CreateToken([FromBody] LoginViewModel model)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(model.Username);

                if (user == null)
                {
                    return(Unauthorized());
                }
                if (_passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
                {
                    var userClaims = await _userManager.GetClaimsAsync(user);

                    var claims = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.NameId, user.Id),
                        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Email, user.Email)
                    }.Union(userClaims);

                    var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._settings.JwtSecurityToken.Key));
                    var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

                    var jwtSecurityToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                        issuer: this._settings.JwtSecurityToken.Issuer,
                        audience: this._settings.JwtSecurityToken.Audience,
                        claims: claims,
                        expires: DateTime.UtcNow.AddMinutes(5),
                        signingCredentials: signingCredentials
                        );
                    return(Ok(new
                    {
                        Token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken),
                        Expiration = jwtSecurityToken.ValidTo,
                        Claims = jwtSecurityToken.Claims
                    }));
                }
                return(Unauthorized());
            }
            catch (Exception ex)
            {
                _logger.LogError($"error while creating token: {ex}");
                return(StatusCode((int)HttpStatusCode.InternalServerError, "error while creating token"));
            }
        }
Пример #13
0
        private string GenerateToken(NguoiDungDangNhap ndDN)
        {
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                claims: new Claim[] {
                new Claim(ClaimTypes.Name, ndDN.TaiKhoan),
                new Claim(ClaimTypes.Role, ndDN.MaLoaiND),
            },
                notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
                signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)


                );

            //string token1 = new JwtSecurityTokenHandler().WriteToken(token);
            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
Пример #14
0
        public static void ReadToken(string jwtToken)
        {
            // To Read Claims on Api Controller

            //var jwt = Request.Headers.Authorization.Parameter;

            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            System.IdentityModel.Tokens.Jwt.JwtSecurityToken token = handler.ReadJwtToken(jwtToken);

            IEnumerable <Claim> claims = token.Claims.ToList();

            string id       = token.Claims.FirstOrDefault(x => x.Type == "id").Value;
            string role     = token.Claims.FirstOrDefault(x => x.Type == "role").Value;
            string Compcode = token.Claims.FirstOrDefault(x => x.Type == "Compcode").Value;
            string Bracode  = token.Claims.FirstOrDefault(x => x.Type == "Bracode").Value;
        }
Пример #15
0
        /// <summary>
        /// Generate user specific JWT string
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GenerateEncodedJWT(OCM.API.Common.Model.User user)
        {
            var claims = new List <System.Security.Claims.Claim>();

            claims.Add(new Claim("UserID", user.ID.ToString()));
            claims.Add(new Claim("nonce", user.CurrentSessionToken.ToString()));


            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.ASCII.GetBytes(user.CurrentSessionToken));

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(ISSUER, AUDIENCE, claims, DateTime.UtcNow, DateTime.UtcNow.AddMonths(1), signingCredentials);

            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Пример #16
0
        public IActionResult Login(string returnUrl, LogInModel model)
        {
            UserProfile findUser = _userService.LogIn(model, out string resultCode);

            if (findUser == null)
            {
                return(Ok(model));
            }

            // 要存的資訊
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, findUser.USER_NO),
                new Claim(ClaimTypes.NameIdentifier, findUser.USER_NO),
                new Claim(ClaimTypes.MobilePhone, findUser.PHONE ?? "")
            };
            var roles = findUser.Roles
                        .Select(r => new Claim(ClaimTypes.Role, LogicCenter.GetEnumName(r.ROLE_ID)));

            claims.AddRange(roles);

            // Json Web Token 登入
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken
                        (
                issuer: Configuration["Tokens:ValidIssuer"],
                audience: Configuration["Tokens:ValidAudience"],
                claims: claims,
                expires: DateTime.UtcNow.AddHours(1),    /* 過期時間 */
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey
                                                               (System.Text.Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])),
                                                           SecurityAlgorithms.HmacSha256)
                        );

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

            return(Ok(
                       new {
                user = findUser,
                token = tokenString
            }));
        }
Пример #17
0
        public IActionResult LoginExternal([FromBody] TokenViewModel jwt)
        {
            var jwtSettings = new JwtSettings
            {
                Key                 = _configuration["jwtSettings:key"],
                Issuer              = _configuration["jwtSettings:issuer"],
                Audience            = _configuration["jwtSettings:audience"],
                MinutesToExpiration = int.Parse(_configuration["jwtSettings:minutesToExpiration"])
            };

            try
            {
                var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(jwt.Token);
                var email = token.Claims.First(c => c.Type == "email");
                var exp   = token.Claims.First(c => c.Type == "exp");
                //var emailVerified = token.Claims.First(c => c.Type == "email_verified");
                if (token.ValidTo > DateTime.UtcNow)
                {
                    var _user = this._userService.Authenticate(email.Value);

                    if (_user != null)
                    {
                        ReadedUserViewModel userViewModel;
                        string tokenString;
                        GetToken(jwtSettings, _user, out userViewModel, out tokenString);
                        return(Ok(new { Token = tokenString, User = userViewModel }));
                    }
                }

                return(Unauthorized());
            }
            catch (Exception)
            {
                return(Unauthorized());
            }
        }