zoukankan      html  css  js  c++  java
  • .net core使用jwt自动续期

               小弟不C才,最近看了下网上的jwt方案,于是自己写了一个简单的jwt方案和大家分享下,希望大家给点意见!

               假如有一个读书网站,可以不用登陆就访问,当需要自己写文章的时候就必须登录,并且登录之后如果一段时间内没有访问,则过期了需要重新登录。有效期内有登录则自动续期,所以我想使用中间件来负责token的更新以及删除。如下部分代码:

         

          public async Task InvokeAsync(HttpContext context)
            {
                try
                {
                    bool isExpires = context.Request.Headers.TryGetValue("isExpires", out StringValues expires);
                    bool IsAuthorized = context.Request.Headers.TryGetValue("Authorization", out StringValues authStr);
                    string token = authStr.ToString().Substring("Bearer ".Length).Trim();
                    //每次访问都更新token有效期
                    new JWT(_cacheClient).RefreshToken(token, isExpires);
                    context.Response.Headers.Add("refreshTokne", token);
                }
                catch (ValidationException)
                {
                    if (context.Request.Path.Value.Contains("api/auth/islogin"))
                    {
                        context.Response.ContentType = "text/plain";
                        await context.Response.WriteAsync("not login");
                    }
                }
                  await _next(context);
            }
    
            /// <summary>
            /// 生成jwtToken,有效期30分钟
            /// </summary>
            /// <param name="claims"></param>
            /// <returns></returns>
            public static string CreateToken(IEnumerable<Claim> claims)
            {
                var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(SecurityKey));
                var expires = DateTime.Now.AddMinutes(30);
                var token = new JwtSecurityToken(
                            issuer: issuer,
                            audience: audience,
                            claims: claims,
                            notBefore: DateTime.Now,
                            expires: expires,
                            signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature));
                string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
                return jwtToken;
            }
            /// <summary>
            /// 更新token,先通过前端传过来的token从redis里取出jwt,如果为null,则表 
            ///示过期或未登录,如果jwt过期,则更新jwt,并且通过中间件把新的token放到响应头里返回前端。
            /// </summary>
            /// <param name="token">token</param>
            /// <param name="isExpires">是否失效</param>
            public  void RefreshToken(string token,bool isExpires=false)
            {
    
                TokenModel tokenMode = _cacheClient.Get<TokenModel>(token);
                if (tokenMode == null)
                    throw new ValidationException("expires");
                JwtSecurityToken jwtSecurityToken= new JwtSecurityTokenHandler().ReadJwtToken(token);
                if(isExpires)
                    token = CreateToken(jwtSecurityToken.Claims);
                tokenMode.ExpireTime = tokenMode.ExpireTime.AddDays(7);
                if(tokenMode.ExpireTime.Day-DateTime.Now.Day==1)//实现最后一天如果访问了就自动续期
                    _cacheClient.Set(token, tokenMode, TimeSpan.FromDays(7));
    
            }
    

      然后前端可以根据响应结果来判断是否跳到登录页。

  • 相关阅读:
    hdu5894 hannnnah_j’s Biological Test(组合数取模)
    HDU5883 The Best Path(并查集+欧拉路)
    HDU5881 Tea(简单题)
    组合数取模
    codeforces703D Mishka and Interesting sum(区间偶数异或)
    upcoj2679 Binary Tree(思路题)
    upcoj2673 It Can Be Arranged(isap)
    atom编辑器适用
    python库pandas
    fabric Node SDK进行连接
  • 原文地址:https://www.cnblogs.com/MrHanBlog/p/11732145.html
Copyright © 2011-2022 走看看