Ejemplo n.º 1
0
        public string GetToken(JWTUserModel user)
        {
            // 创建用户身份标识
            var claims = new Claim[]
            {
                new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString()),
                new Claim(JwtClaimTypes.Id, user.id.ToString(), ClaimValueTypes.Integer32),
                new Claim(JwtClaimTypes.Name, user.Name, ClaimValueTypes.String),
                new Claim(JwtClaimTypes.Scope, user.Power_ID.ToString(), ClaimValueTypes.Integer32)
            };

            // 创建令牌
            var token = new JwtSecurityToken(
                issuer: _jwtSetting.Issuer,
                audience: _jwtSetting.Audience,
                signingCredentials: _jwtSetting.Credentials,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddSeconds(_jwtSetting.ExpireSeconds)
                );

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

            return(jwtToken);
        }
Ejemplo n.º 2
0
        public async Task <JsonResult> LoginGetToken([FromBody] JWTUserModel _user)
        {
            var _return   = await new DB_User().DBLoginAsync(_user);
            var ipaddress = HttpContext.Connection.RemoteIpAddress.ToIPv4String();
            var userAgent = HttpContext.Request.Headers["User-Agent"];
            var agent     = new UserAgent(userAgent);
            var Browser   = $"{agent.Browser?.Name} {agent.Browser?.Version}";
            var OS        = $"{agent.OS?.Name} {agent.OS?.Version}";

            await new DB_Log().SetOperatingLogAsync(new Operatinginfo
            {
                UserID    = _user.id,
                Operating = "登录",
                Date      = DateTime.Now.ToString(),
                UserName  = _user.Name,
                ip        = ipaddress,
                Browser   = Browser,
                OS        = OS,
                state     = _return != null ? 200 : 500,
                Details   = _return != null ? "通过登录授权" : "未通过登录授权"
            });
            var _token = "";

            if (_return != null && !string.IsNullOrEmpty(_return.id.ToString()))
            {
                _token = _tokenServic.GetToken(_user).AESEncrypt();
                HttpContext.AddCookie(CoreConfiguration.JwtCookiesTokenKey, _token);
                return(new JsonResult(new { Success = true, Message = "登录成功", access_token = _token }));
            }
            return(new JsonResult(new { Success = false, Message = "用户名或密码不正确!" }));
        }
        public JWTUserModel GetLoggedUserDetail(string userid)
        {
            DataSet ds = new DataSet(); JWTUserModel userModel = new JWTUserModel();

            try
            {
                string constring = GetConStringFromJson();
                using (SqlConnection con = new SqlConnection(constring))
                {
                    string SqlQuery =
                        "SELECT U.userid,R.role FROM JWTUsers U with (nolock) inner join JWTUsers_Roles R with(nolock) ON U.userid = R.userid where U.userid = '"
                        + userid + "'";

                    SqlDataAdapter da = new SqlDataAdapter(SqlQuery, con);
                    da.Fill(ds);
                }
                if (ds.Tables.Count > 0)
                {
                    userModel.userid = ds.Tables[0].Rows[0][0].ToString();
                    userModel.role   = ds.Tables[0].Rows[0][1].ToString();
                }
            }
            catch (Exception ex)
            {
            }
            return(userModel);
        }
        public JWTUserModel AuthenticateUser(string userid, string password)
        {
            DataSet ds = new DataSet(); JWTUserModel userModel = new JWTUserModel();

            try
            {
                string constring = GetConStringFromJson();
                using (SqlConnection con = new SqlConnection(constring))
                {
                    string SqlQuery = "SELECT userid,email,phoneno,created_date  FROM JWTUsers with(nolock) where userid= '" + userid + "' and password='******'";

                    SqlDataAdapter da = new SqlDataAdapter(SqlQuery, con);
                    da.Fill(ds);
                }
                if (ds.Tables.Count > 0)
                {
                    userModel.userid       = ds.Tables[0].Rows[0][0].ToString();
                    userModel.email        = ds.Tables[0].Rows[0][1].ToString();
                    userModel.phoneno      = ds.Tables[0].Rows[0][2].ToString();
                    userModel.created_date = (DateTime)ds.Tables[3].Rows[0][1];
                }
            }
            catch (Exception ex)
            {
            }
            return(userModel);
        }
        private JWTUserModel AuthenticateUser(string userid, string password)
        {
            DAL dal = new DAL(); JWTUserModel userModel = new JWTUserModel();

            userModel = dal.GetLoggedUserDetail(userid);
            return(userModel);
        }
Ejemplo n.º 6
0
        public async Task <JsonResult> RegisterAsync([FromBody] JWTUserModel _user)
        {
            var _return = await new DB_User().DBRegisterAsync(_user);

            if (_return)
            {
                return(new JsonResult(new { Success = true, Message = "注册成功" }));
            }
            return(new JsonResult(new { Success = false, Message = "注册失败" }));
        }
        public IActionResult Login(string userid = "vamshi", string password = "******")
        {
            JWTUserModel  usermodel = new JWTUserModel();
            IActionResult Response  = Unauthorized();

            usermodel = AuthenticateUser(userid, password);
            if (usermodel != null)
            {
                var tokenstr = GenerateJWTtoken(usermodel);
                Response = Ok(new { token = tokenstr });
            }

            return(Response);
        }
 public IActionResult RefreshToken([FromBody] RefreshTokenModel token)
 {
     try
     {
         JWTUserModel user = JWTSettings.GetNewAccessToken(token);
         if (user == null)
         {
             return(Unauthorized());
         }
         return(Ok(user));
     }
     catch (Exception)
     {
         return(StatusCode(StatusCodes.Status401Unauthorized));
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public async Task <bool> DBRegisterAsync(JWTUserModel _user)
        {
            _user.UserState = 0;
            _user.Power_ID  = 1;

            var connection = CRUD.GetOpenConnection();
            var data       = await connection.GetListAsync <JWTUserModel>(new { _user.Name });

            if (data.ToList().Count != 0)
            {
                return(false);
            }
            else
            {
                CacheFactory.GetCache.Remove(CacheKey);
                await connection.InsertAsync <int, JWTUserModel>(_user);//new JWTUserModel { Name = _user.Name, Pwd = _user.Pwd, UserState = _user.UserState, Power_ID = _user.Power_ID, Remark = _user.Remark }

                return(true);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public async Task <JWTUserModel> DBLoginAsync(JWTUserModel _user)
        {
            var connection = CRUD.GetOpenConnection();
            var _d         = await connection.GetListAsync <JWTUserModel>(new { _user.Name, _user.Pwd });

            if (_d.ToList().Count > 0)
            {
                foreach (JWTUserModel u in _d)
                {
                    _user.id       = u.id;
                    _user.Power_ID = u.Power_ID;
                    _user.Remark   = u.Remark;
                }
                return(_user);
            }
            else
            {
                return(null);
            }
        }
        private string GenerateJWTtoken(JWTUserModel userModel)
        {
            var securitykey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:key"]));
            var credentials = new SigningCredentials(securitykey, SecurityAlgorithms.HmacSha256);
            var claims      = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, userModel.userid),
                new Claim(JwtRegisteredClaimNames.Sub, userModel.role),
            };

            var token = new JwtSecurityToken(
                issuer: _config["Jwt:issuer"],
                audience: _config["Jwt:issuer"],
                claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials
                );
            var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);

            return(encodetoken);
        }
Ejemplo n.º 12
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     JWTUser = JWTSettings.GetJWTUser(HttpContext?.User?.Claims);
 }