Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand token restore and Session in the Analysis of SpringSecurity principle

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand token restore and Session in the analysis of SpringSecurity principle". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "SpringSecurity principle analysis of how to understand token restore and Session" bar!

Original interpretation of SpringSecurity [4]: token restore and Session

Session: commonly known as a session, it has different meanings in different environments. In Spring Security, a session refers to the process from a token authentication request to a logout request on the client side. Web applications are basically based on HTTP protocol, and this protocol is a stateless protocol, two HTTP requests are independent of each other and can not identify each other. In Web applications, especially Spring Security and other security frameworks, multiple requests sent by the same client, if not recognized, each request requires authentication process, which is absolutely a disaster for clients who need to actively provide identification information for each request. So a solution is needed to solve this problem: there is only one solution as a whole: add a global bus to the relevant HTTP requests and flag these HTTP requests uniformly to indicate that they all come from the same identity. At present, there are two mainstream implementations: Session and WebToken, the former is the mainstream standard Web application bus implementation, the logo is on Cookie or URL, and the latter is the mainstream front and rear separation of Web application bus implementation, marking on the request head.

Today, we will focus on the former Session. In JavaEE, Session refers specifically to HttpSession, and its specification is defined and implemented on the server side: by default, each request will have an Session instance.

Public interface HttpSession {/ / creation time long getCreationTime (); boolean isNew (); / / unique ID String getId (); / / Last access time long getLastAccessedTime (); / / Servlet context ServletContext getServletContext (); / / failure capability void invalidate (); void setMaxInactiveInterval (int var1) Int getMaxInactiveInterval (); / / Object getAttribute (String var1) with storage capacity; Enumeration getAttributeNames (); void setAttribute (String var1, Object var2); void removeAttribute (String var1);}

At this point, it can be understood that Session is a storage structure with unique identification and controllable life cycle, and the underlying layer is generally: ConcurrentMap.

Session tracking

Session tracking: SessionTracking, which means to trace the source of Session, that is, where to start looking for bus tags. Cookie and URL,@since Servlet 3.0 are configurable by default.

Public enum SessionTrackingMode {COOKIE, URL, SSL}

Cookie writes sessionId to Cookie,URL and sessionId to URL when redirected. Parsing Cookie or URL is done within HttpServer, such as tomcat, undertow. Therefore, you generally do not see the details of Session construction (different servers have different implementations). For example, Tomcat servers are CoyoteAdapter#postParseRequest when building Request, and the order of parsing SessionId is URL-> Cookie-- > SSL, and Cookie has the highest priority, followed by URL.

Although you don't need to know how to parse Session, JavaEE gives the build entry and build requirements: HttpServletRequest#getSession. By default, the construction of session is left to HttpServer, but for distributed applications, the Spring Session module can take over the lifecycle of Session.

Note that if the session tracking ID is lost, it will result in Session==null, and all subsequent features that rely on Session storage will fail: for example: CsrfFilter

/ / actively determine whether the returned Session needs to rebuild HttpSession getSession (boolean var1); / / get the Session instance of the current request, and build HttpSession getSession () if it does not exist; / / modify SessionIdString changeSessionId (); / / Session validity: whether to survive boolean isRequestedSessionIdValid (); / / Session build source: whether to parse boolean isRequestedSessionIdFromCookie () from Cookie; / / Session build source: whether to parse boolean isRequestedSessionIdFromURL () from URL

After perfecting the token on the server side in Spring Security, you can see from the diagram of the previous article: after the token is complete, it is managed by Session, Context and Cookie.

The processing of Session is performed through SessionAuthenticationStrategy. The default is Composite policy, built-in: ChangeSessionIdAuthenticationStrategy, reuse existing Session, modify its unique identity.

CsrfAuthenticationStrategy (org.springframework.security.web.csrf) ConcurrentSessionControlAuthenticationStrategy (org.springframework.security.web.authentication.session) RegisterSessionAuthenticationStrategy (org.springframework.security.web.authentication.session) CompositeSessionAuthenticationStrategy (org.springframework.security.web.authentication.session) NullAuthenticatedSessionStrategy (org.springframework.security.web.authentication.session) AbstractSessionFixationProtectionStrategy (org.springframework.security.web.authentication.session) ChangeSessionIdAuthenticationStrategy (org.springframework.security.web.authentication.session) SessionFixationProtectionStrategy (org.springframework.security.web.authentication.session)

After Session has made a criminal record, it can be obtained and restored in subsequent requests.

Token restore

There is a high priority filter in Spring Security: SecurityContextPersistenceFilter: context persistence filter, remember that getting the full server token in FilterSecurityInterceptor is obtained from SecurityContext?

SecurityContext contextBeforeChainExecution = securityContextRepository.loadContext (holder)

There is a SecurityContextRepository, the security context repository, and the default is HttpSessionSecurityContextRepository, which is the context obtained from HttpSession. HttpSession has been restored in session tracking.

/ /-- session storage-/ / get the SessionHttpSession httpSession = request.getSession (false) in the request first; / / get SecurityContextSecurityContext context = readSecurityContextFromSession (httpSession) from Session / / context is to get Object contextFromSession = httpSession.getAttribute (springSecurityContextKey) from key= "SPRING_SECURITY_CONTEXT" in ConcurrentMap; / /-- context storage-SecurityContextHolder.setContext (context)

At this point, the overall process of Session is clear, and the overall diagram is as follows:

Session configuration

The details of Session are left to the server to set, but the configuration API of Session is standardized:

Public interface SessionCookieConfig {/ / name configuration: common: JSESSIONID void setName (String var1); String getName (); / / set the request domain name / / suffix matching that can carry Cookie. Format: dot + domain name void setDomain (String var1); String getDomain () / / set the request path that can carry Cookie / / prefix matching: part of the URL immediately after the domain name. Default: / void setPath (String var1); String getPath (); / / set additional remarks void setComment (String var1); String getComment (); / / whether to allow the client to operate Cookie void setHttpOnly (boolean var1); boolean isHttpOnly () / / set the request method that can carry Cookie: / / ture: https,false: http, https void setSecure (boolean var1); boolean isSecure (); / / validity period configuration. Default is-1. Common: 3600 void setMaxAge (int var1); int getMaxAge ();}

Spring has a corresponding configuration class for the Session of Server, which will be configured into Servlet when the container starts. Example:

Server.servlet.context-path= / ctxserver.servlet.session.cookie.name= Authorizationserver.servlet.session.cookie.path= / ctx/cookie/server.servlet.session.cookie.max-age=3600server.servlet.session.cookie.http-only=trueserver.servlet.session.cookie.secure=falseserver.servlet.session.cookie.comment=new cookie name

Browser:

Set-Cookie: Authorization=_xkjjuKHOrOLbS3KRlUmOrRYYn-Z9oa-cLCLWS54; Version=1; Path=/ctx/cookie/; HttpOnly; Max-Age=3600; Expires=Mon, 26-Oct-2020 02:25:57 GMT; Comment= "new cookie name"

Follow-up carrying Cookie

Cookie: Authorization=dhiWDzOksYItVwcqIZAew0YQqtA8BI9DZIVUXWjK

Note: the path for Cookie defaults to "/", which means that any page that carries Cookie will be the same. If configured to other values, make sure that the authentication path of the Spring Security matches the incoming transport Cookie. The configuration format should be: "contextPath/ match value path /", which means that both the matching path and its subpaths will carry the Cookie generated by the matching path request.

At this point, I believe you have a deeper understanding of "SpringSecurity principle analysis of how to understand token restore and Session". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report