Simple login System Based on RFC6265 (HTTP Status Management Protocol)

Source: Internet
Author: User
Tags http cookie

This protocol mainly describes how to use HTTP Cookie and SetCookie header fields to implement HTTP Request

Status tracking and management. This is an important application in user behavior analysis, login system design, and other methods. Pair

Most modern browsers support RFC6265.

 

Basic Principles:

RFC6265 describes how to set different values of SetCookie in HTTPResponse to tell the browser client

The values and actions specified in Response are included in each Request Header. Until the server

The configured session expires. Use Tomcat to set the session expiration time to 30 minutes and configure it in web. xml

This attribute value can be overwritten in the file. When the user closes the browser

The cookie content will be automatically destroyed. This may be inconvenient for users, so many websites provide the ability to remember their accounts.

The reason is that the cookie is written to a local file.

 

System Access and redirection to the logon page

First, when the browser client initiates a Request to access the specified URL or Web Server, the Server

Check whether the request header contains the Cookie field and the content in the Cookie field to determine whether the visitor is

Is a logon user or a user not logged on. If the user is not logged on to the page, redirect the URL to the logon page. User

After logging on to the server, the server sends an HTTP Response + Set-Cookie to the client browser.

Then, all the URLs sent to this Domain will carry the content specified in Set-Cookie.

Request + Cookie to the server, the server checks the Cookie content in the Request header to implement

User status tracking. In this way, the stateless HTTP Request is converted into a stateful HTTP connection.

Management. The basic flowchart of logon is as follows:


Sending and receiving status of HTTP requests from servers and clients:


User logout system and Request termination

When the client closes the browser, the client Cookie will be automatically discarded from the memory.

When you open a browser to request server resources, you will be asked to log on to the server again to create a new trackable

When the Request session exceeds the session time configured on the server, the user is also required to log on to the system again.

When the user Exits normally using the system exit function, remove it by setting Max-Age: 0.

The current cookie content is used to clear the client status. As long as the Cookie is added to the HTTP Response

Set an expiration time for the period attribute at the same time. Example:


RFC6265 details about the attributes and usage of cookies and setcookies

Cookie

SetCookie

HTTP Request Header. The user client sends authentication information and other useful information to the server, which is used to track the client status and analyze user behavior.

HTTP Response is used to send specified status information to the client and establish contact with the client. By setting the HTTPOnly attribute and Secure attribute, you can also protect the client's Cookie data to prevent malicious reading of user Cookie information.

RFC6265 is a simple example:

= Server-> UserAgent = // the Server is sent to the client

Set-Cookie: SID = 31d4d96e407aad42

= User Agent-> Server ==/// each request carries the SID information to track the User status.

Cookie: SID = 31d4d96e407aad42

The Request Path of the client must contain the SID information.

= Server-> UserAgent =

Set-Cookie: SID = 31d4d96e407aad42; Path =/; Domain = example.com

= User Agent-> Server =

Cookie: SID = 31d4d96e407aad42

Delete the SID information in the client Request Cookie, and obtain any time before the current time.

= Server-> UserAgent =

Set-Cookie: SID =; Expires = Sun, 06 Nov 1994 08:49:37 GMT

Finally, let's take a look at the Cookie information that I captured after logging on to CSDN:

In J2EE, when the SessionID method is called from the HTTP Servlet Request, the JSESSIONID

Set the Cookie to the Response header. So you do not need to call it again explicitly!

According to RFC6265, based on Spring3 MVC, I also implemented a simple login system design.

This helps you better understand the protocol. There are only two pages, two Controller classes and one ServletFilter

The functions of each class are as follows:

ServletFilter class: checks the HTTP Request header and tracks the user status.

Two Controller classes: one for managing user login and logout, and the other for simply obtaining homepage information

The ServletFilter class code is as follows:

package com.edinme.exam.filter;import java.io.IOException;import java.util.Date;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.editme.exam.util.FilterUtil;public class SingleSignOnFilter implements Filter{ @Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {HttpServletRequest httpRequest = (HttpServletRequest) request;HttpServletResponse httpResponse = (HttpServletResponse) response;String ipAddress = httpRequest.getRemoteAddr();// get URI resource pathString uriPath = httpRequest.getRequestURI();String contextPath = httpRequest.getContextPath();String cookie = httpRequest.getHeader("Cookie");String sessionId = httpRequest.getSession().getId(); // enable SetCookie header in HTTP Responseif(FilterUtil.validURLRequest(uriPath, cookie, contextPath, sessionId)){System.out.println("Request URI : " + uriPath);System.out.println("IP "+ipAddress + ", Time " + new Date().toString());chain.doFilter(request, response);}else{System.out.println(httpRequest.getProtocol() + httpRequest.getLocalPort() + httpRequest.getContextPath());httpResponse.sendRedirect("/exam/user.do");}}@Overridepublic void init(FilterConfig config) throws ServletException {// TODO Auto-generated method stub}}
Log on to and log out of the Controller:

package com.edinme.exam.controller;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.edinme.exam.dto.MockUpDataFactory;import com.edinme.exam.dto.UserDto;import com.editme.exam.util.FilterUtil;@Controller@RequestMapping(value = "/user")public class UserLoginController {@RequestMapping(method = RequestMethod.GET)public ModelAndView goLoginPage(){System.out.println("Dispaly SSO Page");ModelAndView view = new ModelAndView("user");return view;}@RequestMapping(value = "signIn", method = RequestMethod.GET)@ResponseBodypublic UserDto login(@RequestParam String userId, @RequestParam String password, /*HttpServletRequest httpRequest,*/ HttpServletResponse response){System.out.println("User Name = " + userId);MockUpDataFactory dataFactory = new MockUpDataFactory();response.addHeader("Set-Cookie", "userId=" + userId + "; Path=" + FilterUtil.CONTEXT_PATH + "; HttpOnly");return dataFactory.getUserById(userId);}@RequestMapping(value = "signOut", method = RequestMethod.GET)@ResponseBodypublic UserDto logout(@RequestParam String userId, HttpServletRequest httpRequest, HttpServletResponse response){MockUpDataFactory dataFactory = new MockUpDataFactory();//Set-Cookie:JSESSIONID=delete; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/exam///Set-Cookie:userId=delete; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=/exam/Cookie[] cs = httpRequest.getCookies();for(Cookie c : cs){c.setMaxAge(0); // set expire attributec.setValue("delete");c.setPath(FilterUtil.CONTEXT_PATH); // set path, must be same as login context pathresponse.addCookie(c);}response.setHeader("Expires", "Thu, 19 Nov 1981 08:52:00 GMT"); // must be GTM formatreturn dataFactory.getUserById(userId);}////public static void main(String[] args)//{//SimpleDateFormat sdf = new SimpleDateFormat("E dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));//System.out.println(sdf.format(new Date()));//}}
Click here to download all source code:

Http://download.csdn.net/detail/jia20003/7087947

Think it's better. Please try it out !!, Thank you !!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.