【转】C#根据用户信息,生成token和cookie的方法

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

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

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

  1. 项目的引用里,右键:管理NuGet程序包
  2. 搜索JWT,安装即可,要注意项目的.NetFrameWork 要大于等于4.6
    【转】C#根据用户信息,生成token和cookie的方法
  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;
        }
    }
上一篇:C#-使用javascript的FormsAuthentication.SignOut()


下一篇:ASP.NET MVC项目Forms身份验证HttpContext.Current.User为空