MVC save a token in session

前端 未结 4 1678
我寻月下人不归
我寻月下人不归 2021-01-14 01:22

I am calling a service, and I need to pass the user\'s permanent security token with every request I make.

In order to do that, I\'ve added this method to my base

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-14 02:15

    You can place the users security token, IP address, and a time-stamp in a string. Encrypt the string with a symmetric algorithm such as AES and place it as a cookie. Then change your code to read from the cookie. You can validate that the ip address in the cookie matches the users ip address, this will prevent someone stealing the cookie value and replaying it. Here is the MSDN documentation on AES (Rjindael is the original name). In this scheme, the token will not expire until the cookie expires and/or your timeout is reached. I do highly recommend you put a timeout and not make it forever or persistent, it will make the scheme less secure to exclude a timeout. Also put the time-stamp at the beginning of your cookie value, because of CBC mode on these algorithms it will affect the way the encrypted string looks because of the changes in bits at the begining (Avalanche effect).

    The ASP.NET membership provider also has an authentication cookie so this cookie should not expire before the membership cookie. Sessions have to expire on a timeout because there is no guarantee that the user is still there as HTTP is stateless whereas the cookie is under the control of the user and is passed every single time a request is made.

    getUsr function

    protected UserData getUsr()
    {
        try
        {
            UserData usr = new UserData();
    
            string token = Request.Cookies["secToken"].Value;
    
            // implement RijndaelManaged encryption/decryption scheme
            // this can also be serialized as an object to make cleaner
            var tokenValues = Decrypt(token).Split(',');
    
            // The timeout expired
            if (DateTime.Now > DateTime.Parse(tokenValues[1]))
            {
                throw new Exception("Timeout");
            }
    
            // someone stole this cookie or is on a different internet connection
            if (tokenValues[0] != System.Web.HttpContext.Current.Request.UserHostAddress)
            {
                throw new Exception("Invalid IP");
            }
    
            // You're ok everything checks out
            usr.SecurityToken = tokenValues[3].ToString();
    
            MembershipUser mvcUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            usr.Id = (int)mvcUser.ProviderUserKey;
    
            return usr;
        }
        catch (Exception ex)
        {
            log.Debug("Could not create usr object", ex);
            throw new Exception("Could not authenticate");
        }
    }
    

提交回复
热议问题