C. how to generate token s and cookie s based on user information

Keywords: Javascript JSON

In projects with separate front and back ends, the process of requesting interfaces is generally as follows:

  1. User login with username and password
  2. The information is correct, and the interface returns token
  3. To request the interface that needs to be logged in for verification, put the token into the header to request the interface together

Here's how token is generated in webapi project

  1. In the project reference, right-click: manage NuGet package
  2. Search JWT and install it. Note that the. NetFrameWork of the project should be greater than or equal to 4.6

  1. The code is as follows
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";//This server encryption key belongs to the private key
    private static JavaScriptSerializer myJson = new JavaScriptSerializer();
    public static string GenToken(TokenInfo M)
    {
        var payload = new Dictionary<string, dynamic>
            {
                {"UserName", M.UserName},//Used to store the account information of the current login
                {"UserPwd", M.Pwd}//Used to store the login password information of the current login
            };
        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;
        }
    }
}

The same is true for using cookies. After users log in, they generate cookies with specific methods and return them to the browser. Every time the browser requests an interface or accesses a page, it will bring cookie information for authentication
c. how to generate cookie s:

public class UserModel
{
    public string UserName { get; set; }
    public string Pwd { get; set; }
}

public class CookieHelper
{
    private static JavaScriptSerializer myJson = new JavaScriptSerializer();

    /// <summary>
    ///Set login cookie
    /// </summary>
    /// <param name="model"></param>
    public static void SetUserCookie(UserModel model)
    {
        FormsAuthentication.SetAuthCookie(model.UserName, false);
        string userStr = myJson.Serialize(model);
        //Create ticket
        FormsAuthenticationTicket ticket = 
            new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, 
            DateTime.Now + FormsAuthentication.Timeout, false, userStr);
        //encryption
        var cookieValue = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Domain = FormsAuthentication.CookieDomain,
            Path = FormsAuthentication.FormsCookiePath
        };
        //Write to cookie
        HttpContext.Current.Response.Cookies.Remove(cookie.Name);
        HttpContext.Current.Response.Cookies.Add(cookie);
    }

    /// <summary>
    ///Cookies for getting login information
    /// </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;
    }
}

Posted by mwl707 on Tue, 05 Nov 2019 08:02:40 -0800