C根据用户信息生成token和cookie的方法

8次阅读

共计 2972 个字符,预计需要花费 8 分钟才能阅读完成。

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

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

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

  1. 项目的引用里,右键:管理 NuGet 程序包
  2. 搜索 JWT,安装即可,要注意项目的.NetFrameWork 要大于等于 4.6

  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;
    }
}

正文完
 0