内容简介:在前后端分离的项目里,我们请求接口的流程一般是:这里介绍一下,在webapi项目里,token是怎么生成的
在前后端分离的项目里,我们请求接口的流程一般是:
- 用户使用用户名密码登录
- 信息正确,接口返回token
- 请求需要登录验证的接口,将token放到header里一起请求接口
这里介绍一下,在webapi项目里,token是怎么生成的
- 项目的引用里,右键:管理NuGet程序包
- 搜索JWT,安装即可,要注意项目的.NetFrameWork 要大于等于4.6
- 代码如下
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; } } }
使用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#根据用户信息,生成token和cookie的方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- 模拟测试数据的生成方法
- 谈谈全局唯一ID生成方法
- NumPy 如何生成多维数组的方法
- 3 种生成高强度密码的方法
- 3种生成高强度密码的方法
- [译] 高效的文本生成方法:LaserTagger 现已开源
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
About Face 2.0
Alan Cooper、Robert M. Reimann / Wiley / March 17, 2003 / USD 35.00
First published seven years ago-just before the World Wide Web exploded into dominance in the software world-About Face rapidly became a bestseller. While the ideas and principles in the original book......一起来看看 《About Face 2.0》 这本书的介绍吧!