zoukankan      html  css  js  c++  java
  • 【转】C#根据用户信息,生成token和cookie的方法

    在前后端分离的项目里,我们请求接口的流程一般是:

    1. 用户使用用户名密码登录
    2. 信息正确,接口返回token
    3. 请求需要登录验证的接口,将token放到header里一起请求接口

    这里介绍一下,在webapi项目里,token是怎么生成的?

    1. 项目的引用里,右键:管理NuGet程序包
    2. 搜索JWT,安装即可,要注意项目的.NetFrameWork 要大于等于4.6
    3. 代码如下:
      public class TokenInfo
      {
          public TokenInfo()
          {
              UserName = "jack.chen";
              Pwd = "jack123456";
          }
          public string UserName { get; set; }
          public string Pwd { get; set; }
      }
      
      public class TokenHelper
      {
          public static string SecretKey = "This is a private key for Server";//这个服务端加密秘钥 属于私钥
          private static JavaScriptSerializer myJson = new JavaScriptSerializer();
          public static string GenToken(TokenInfo M)
          {
              var payload = new Dictionary<string, dynamic>
                  {
                      {"UserName", M.UserName},//用于存放当前登录人账户信息
                      {"UserPwd", M.Pwd}//用于存放当前登录人登录密码信息
                  };
              IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
              IJsonSerializer serializer = new JsonNetSerializer();
              IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
              IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
              return encoder.Encode(payload, SecretKey);
          }
      
          public static TokenInfo DecodeToken(string token)
          {
              try
              {
                  var json = GetTokenJson(token);
                  TokenInfo info = myJson.Deserialize<TokenInfo>(json);
                  return info;
              }
              catch (Exception)
              {
      
                  throw;
              }
          }
      
          public static string GetTokenJson(string token)
          {
              try
              {
                  IJsonSerializer serializer = new JsonNetSerializer();
                  IDateTimeProvider provider = new UtcDateTimeProvider();
                  IJwtValidator validator = new JwtValidator(serializer, provider);
                  IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                  IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                  var json = decoder.Decode(token, SecretKey, verify: true);
                  return json;
              }
              catch (Exception)
              {
                  throw;
              }
          }
      }
    4. 使用cookie也是一样,用户登录之后,用特定的方法生成cookie,返回到浏览器,浏览器每次请求接口或者访问页面的时候,都会带上cookie信息,用于身份验证
      c#生成cookie的方法
      public class UserModel
      {
          public string UserName { get; set; }
          public string Pwd { get; set; }
      }
      
      public class CookieHelper
      {
          private static JavaScriptSerializer myJson = new JavaScriptSerializer();
      
          /// <summary>
          /// 设置登录信息cookie
          /// </summary>
          /// <param name="model"></param>
          public static void SetUserCookie(UserModel model)
          {
              FormsAuthentication.SetAuthCookie(model.UserName, false);
              string userStr = myJson.Serialize(model);
              //创建ticket
              FormsAuthenticationTicket ticket = 
                  new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, 
                  DateTime.Now + FormsAuthentication.Timeout, false, userStr);
              //加密
              var cookieValue = FormsAuthentication.Encrypt(ticket);
              var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
              {
                  HttpOnly = true,
                  Secure = FormsAuthentication.RequireSSL,
                  Domain = FormsAuthentication.CookieDomain,
                  Path = FormsAuthentication.FormsCookiePath
              };
              //写入cookie
              HttpContext.Current.Response.Cookies.Remove(cookie.Name);
              HttpContext.Current.Response.Cookies.Add(cookie);
          }
      
          /// <summary>
          /// 获取登录信息的cookie
          /// </summary>
          /// <returns></returns>
          public static UserModel GetUserCookie()
          {
              var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
              if (object.Equals(cookie, null) || string.IsNullOrEmpty(cookie.Value))
              {
                  return null;
              }
              try
              {
                  var ticket = FormsAuthentication.Decrypt(cookie.Value);
                  if (!object.Equals(ticket, null) && !string.IsNullOrEmpty(ticket.UserData))
                  {
                      UserModel userData = myJson.Deserialize<UserModel>(ticket.UserData);
                      return userData;
                  }
              }
              catch (Exception)
              {
                  
              }
              return null;
          }
      }
  • 相关阅读:
    openCV的imread()函数
    python 文件操作(open函数)
    opencv函数解析
    python face_reconnition库函数解析
    python—OpenCV2中 cv2.VideoCapture(),read(),waitKey()的使用
    数据结构之各排序算法
    C语言格式符
    利用函数对数组排序,是否会修改原数组
    保研夏令营证书扫描工具推荐
    一些小技巧
  • 原文地址:https://www.cnblogs.com/chriskwok/p/12599130.html
Copyright © 2011-2022 走看看