Log in to connect user information with token Load into redis In the middle ,

take token And part of the user information is stored in cookie in ,

Next time you log in Judge cookie Of token stay redis Whether there is ,

If it exists, load the user information and log in automatically .

public class LoginFormPrincipal : IPrincipal
{
private IIdentity _identity; public LoginFormPrincipal(LoginFormIdentity loginFormIdentity)
{
if (loginFormIdentity == null)
{
throw new ArgumentNullException("loginFormIdentity");
}
_identity = loginFormIdentity;
} public IIdentity Identity
{
get
{
return _identity;
}
} public bool IsInRole(string role)
{
throw new Exception("");
} public bool SignOut()
{
FormsAuthentication.SignOut();
HttpContext.Current.Session.Abandon();
return true;
} public static void SignIn(string CurrentId, string Token, int expiration)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(, CurrentId, DateTime.Now, DateTime.Now.AddDays(), true, Token);
string cookieValue = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
cookie.HttpOnly = true;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
if (expiration > )
{
cookie.Expires = DateTime.Now.AddMinutes(expiration);
}
HttpContext context = HttpContext.Current;
if (context == null)
{
throw new InvalidOperationException();
}
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie); } private static FormsAuthenticationTicket TryParseAuthenticationTicket(HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
HttpCookie cookie = request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
{
return null;
}
try
{
return FormsAuthentication.Decrypt(cookie.Value);
}
catch
{
}
return null;
} private static LoginFormPrincipal TryParsePrincipal(HttpRequest request)
{
FormsAuthenticationTicket ticket = TryParseAuthenticationTicket(request);
if (ticket == null)
{
return null;
}
int UserId = ;
if (!int.TryParse(ticket.Name, out UserId))
{
return null;
}
string Token = ticket.UserData;
if (string.IsNullOrEmpty(Token))
{
return null;
} return new LoginFormPrincipal(new LoginFormIdentity(UserId, Token));
} public static void TrySetUserInfo(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
LoginFormPrincipal user = TryParsePrincipal(context.Request);
if (user != null)
{
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
cookie.Expires = DateTime.Now.AddMinutes();
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie);
context.User = user;
string key = string.Format(RedisKeys.CurrentUser, user.Identity.Name + user.Identity.AuthenticationType);
RedisBase.SetListExpire(key, DateTime.Now.AddMinutes()); }
else
{
context.User = user;
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
cookie.Expires = new DateTime(, , );
context.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
context.Response.Cookies.Add(cookie);
} } }
} public class LoginFormIdentity : IIdentity
{
private string _userId;
private string _token; public LoginFormIdentity(int UserId, string Token)
{
_userId = UserId.ToString();
_token = Token;
} public string AuthenticationType
{
get { return _token; }
} public bool IsAuthenticated
{
get { return true; }
} public string Name
{
get { return _userId; }
}
}

redis + cookies More articles on persistent login

  1. Django,COOKIES,SESSION Complete user login

    1.urls.py """Django_cookie_session URL Configuration The `urlpatterns` list routes UR ...

  2. python Get Taobao login cookies

    a key : Go to Sina Weibo login interface to login One . Code # coding=utf-8 import requests from selenium.webdriver.common.by import By from ...

  3. [ASP.NET MVC] ASP.NET Identity Login technology application

    [ASP.NET MVC] ASP.NET Identity Login technology application scene ASP.NET Identity It's an open source project contributed by Microsoft , To provide with ASP.NET Validation of the . Authorization and so on . stay ASP.NET I ...

  4. struts2 Custom interceptors and cookie Integration enables users to avoid repeated login

    Purpose : Test Development , In order to reduce the user login this cumbersome login verification , Just use struts2 Made a simple struts2 Interceptor , It's related to cookie Integrate , See the code specifically structure ( Two parts )=struts2.xml+ Custom interceptors ...

  5. Python Reptiles - Try using labor and OCR Handle captcha simulation login

    At the beginning, people have been saying that Zhihu has inverted Chinese character verification code when logging into the home page , I open my own Zhihu login page , Found only the account number and password , Where did they say the inverted captcha go , Think about it carefully. I have logged in before , It should be local cookies, Then I ...

  6. uploadify Cookie Verify login and upload problems

    When uploading a file, you must verify that you are logged in . When used FormsAuthentication Do login , Use FormsAuthentication.FormsCookieName Verify that you have logged in . <scrip ...

  7. Spring Boot SSO Single sign in

    https://github.com/ITDragonBlog/daydayup/tree/master/SpringBoot-SSO flow chart : 1: Redis Save user information To Redis(KEY- ...

  8. PHP Log in to the website and grab the data

    Sometimes you need to log on to the website , And then grab some useful information , If it's done manually , Too tired . Some people can log in very quickly , But you need to visit other pages after you log in, and you can't visit them all the time , Because they didn't bring Cookie Go in and be treated as two conversations . Let's take a look at Dai ...

  9. [ turn ] To solve IE10 The browser doesn't work ASP.NET Form verification login problem

    It's online on the client this morning , When the program is deployed to the official machine, we find that our website only has IE10 The browser failed to log in , Any other browser version or use a lower IE All versions can log in normally , Use IE Compatibility view can also log in normally , I want to say yes ...

Random recommendation

  1. VMware Next to the virtual machine Ubuntu14 System partition sda1 Disk expansion

    VMware Next to the virtual machine Ubuntu14 System partition sda1 Disk expansion Generally speaking , In the virtual machine Ubuntu When expanding the disk under , It's all about adding new partitions , Instead of expanding the partition where the system is located , As in this link http ...

  2. Spring Boot Project release to Docker

    Let's have a chat first I've been in the business class application My colleagues in operation and maintenance must have deep feelings , Every application It's a mix of functions , Data exchange is a mess ( Of course, it has to do with top-level business design ), Dozens of application Release ...

  3. Form Dynamic drop-down box

    FORM Level trigger :WHEN-NEW-FORM-INSTANCE   1. Definition :      V_LIST_NAME11 VARCHAR2(100) := 'QUERY_FIND.UPDATE_TYPE' ...

  4. C++ Realization RTMP Protocol delivery H.264 Coding and AAC Encoded audio and video

    http://www.cnblogs.com/haibindev/archive/2011/12/29/2305712.html C++ Realization RTMP Protocol delivery H.264 Coding and AAC Encoded audio and video RTMP ...

  5. visual studio Verify the use of controls in

    1.RequiredFieldValidator: Verify a required field , If this field is not filled in , that , Will not be able to submit information . RequiredFieldValidator Control , It mainly sets three properties : (1)ErrorM ...

  6. 【 Math related 、 law 】Codeforces 696B Puzzles

    Topic link : http://codeforces.com/problemset/problem/696/B The main idea of the topic : Give a tree , Start recursion from the root ,time=1, Each time recursion equal probability random access to the node's children , ...

  7. mvc Paging generates static pages ,mvc Generate static pages

    http://blog.csdn.net/xxj_jing/article/details/7899125 Paging generates static pages http://www.cnblogs.com/luanyilin/archi ...

  8. CKEditor Extension plug-in : Automatic typesetting function

    CKEditor It's a new generation of FCKeditor, It's a redeveloped version .CKEditor It's one of the best online text editors in the world , Because of its amazing performance and scalability, it is widely used in major websites . If you haven't touched it, you can have a look , ...

  9. #include &lt;map&gt;

    //tuple Multivariate arrays , Must be a static array , Similar structures // coordination array,vector Use //std::tuple< Array element type > Array variable name ( Array element variable name ); #include < ...

  10. good Python Learning resources

    good Python Learning resources collection ( Strongly recommend )   Python It's an object-oriented . Literal computer programming language . Its grammar is simple and clear , Try to use English words with no different meanings , Unlike most other programming languages that use braces , It uses ...