C#依据用户信息,天生token和cookie的要领

在前后端星散的项目里,我们要求接口的流程平常是:

  1. 用户运用用户名暗码登录
  2. 信息准确,接口返回token
  3. 要求须要登录考证的接口,将token放到header里一同要求接口

这里引见一下,在webapi项目里,token是怎样天生的

  1. 项目的援用里,右键:治理NuGet程序包
  2. 搜刮JWT,装置即可,要注意项目的.NetFrameWork 要大于即是4.6

《C#依据用户信息,天生token和cookie的要领》

  1. 代码以下
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;
    }
}
    原文作者:上帝遗忘之子
    原文地址: https://segmentfault.com/a/1190000019280749
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞