Spring security 是一个能高度定制的身份验证和访问控制框架, 是基于 Spring 应用程序标准. 相似的的框架有 Shrio, 相比于 Spring security, Shrio 更轻一些. Spring secuity 对于 Spring 框架的兼容性更好, 但同时也更依赖于 Spring 框架.
Disables encoding URLs using the HttpServletResponse to prevent including the session id in URLs which is not considered URL because the session id can be leaked in things like HTTP access logs.
Provides integration between the SecurityContext and Spring Web’s WebAsyncManager by using the SecurityContextCallableProcessingInterceptor.beforeConcurrentHandling(org.springframework.web.context.request.NativeWebRequest, Callable) to populate the SecurityContext on the Callable.
Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder. By default it uses an HttpSessionSecurityContextRepository. See this class for information HttpSession related configuration options. This filter will only execute once per request, to resolve servlet container (specifically Weblogic) incompatibilities. This filter MUST be executed BEFORE any authentication processing mechanisms. Authentication processing mechanisms (e.g. BASIC, CAS processing filters etc) expect the SecurityContextHolder to contain a valid SecurityContext by the time they execute. This is essentially a refactoring of the old HttpSessionContextIntegrationFilter to delegate the storage issues to a separate strategy, allowing for more customization in the way the security context is maintained between requests. The forceEagerSessionCreation property can be used to ensure that a session is always available before the filter chain executes (the default is false, as this is resource intensive and not recommended).
A javax.servlet.Filter that uses the SecurityContextRepository to obtain the SecurityContext and set it on the SecurityContextHolder. This is similar to SecurityContextPersistenceFilter except that the SecurityContextRepository.saveContext(SecurityContext, HttpServletRequest, HttpServletResponse) must be explicitly invoked to save the SecurityContext. This improves the efficiency and provides better flexibility by allowing different authentication mechanisms to choose individually if authentication should be persisted.
Filter implementation to add headers to the current response. Can be useful to add certain headers which enable browser protection. Like X-Frame-Options, X-XSS-Protection and X-Content-Type-Options.
Applies CSRF protection using a synchronizer token pattern. Developers are required to ensure that CsrfFilter is invoked for any request that allows state to change. Typically this just means that they should ensure their web application follows proper REST semantics (i.e. do not change state with the HTTP methods GET, HEAD, TRACE, OPTIONS). Typically the CsrfTokenRepository implementation chooses to store the CsrfToken in HttpSession with HttpSessionCsrfTokenRepository wrapped by a LazyCsrfTokenRepository. This is preferred to storing the token in a cookie which can be modified by a client application.
Logs a principal out. Polls a series of LogoutHandlers. The handlers should be specified in the order they are required. Generally you will want to call logout handlers TokenBasedRememberMeServices and SecurityContextLogoutHandler (in that order). After logout, a redirect will be performed to the URL determined by either the configured LogoutSuccessHandler or the logoutSuccessUrl, depending on which constructor was used.
Processes an authentication form submission. Called AuthenticationProcessingFilter prior to Spring Security 3.0. Login forms must present two parameters to this filter: a username and password. The default parameter names to use are contained in the static fields SPRING_SECURITY_FORM_USERNAME_KEY and SPRING_SECURITY_FORM_PASSWORD_KEY. The parameter names can also be changed by setting the usernameParameter and passwordParameter properties. This filter by default responds to the URL /login.
For internal use with namespace configuration in the case where a user doesn’t configure a login page. The configuration code will insert this filter in the chain instead. Will only work if a redirect is used to the login page.
Processes a HTTP request’s BASIC authorization headers, putting the result into the SecurityContextHolder. For a detailed background on what this filter is designed to process, refer to RFC 1945, Section 11.1 . Any realm name presented in the HTTP request is ignored. In summary, this filter is responsible for processing any request that has a HTTP request header of Authorization with an authentication scheme of Basic and a Base64-encoded username:password token. For example, to authenticate user “Aladdin” with password “open sesame” the following header would be presented: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== This filter can be used to provide BASIC authentication services to both remoting protocol clients (such as Hessian and SOAP) as well as standard user agents (such as Internet Explorer and Netscape). If authentication is successful, the resulting Authentication object will be placed into the SecurityContextHolder. If authentication fails and ignoreFailure is false (the default), an AuthenticationEntryPoint implementation is called (unless the ignoreFailure property is set to true). Usually this should be BasicAuthenticationEntryPoint, which will prompt the user to authenticate again via BASIC authentication. Basic authentication is an attractive protocol because it is simple and widely deployed. However, it still transmits a password in clear text and as such is undesirable in many situations. Digest authentication is also provided by Spring Security and should be used instead of Basic authentication wherever possible. See DigestAuthenticationFilter. Note that if a RememberMeServices is set, this filter will automatically send back remember-me details to the client. Therefore, subsequent requests will not need to present a BASIC authentication header as they will be authenticated using the remember-me mechanism.
Responsible for reconstituting the saved request if one is cached and it matches the current request. It will call getMatchingRequest on the configured RequestCache. If the method returns a value (a wrapper of the saved request), it will pass this to the filter chain’s doFilter method. If null is returned by the cache, the original request is used and the filter has no effect.
A Filter which populates the ServletRequest with a request wrapper which implements the servlet API security methods. SecurityContextHolderAwareRequestWrapper is extended to provide the following additional methods:
HttpServletRequest.authenticate(HttpServletResponse) - Allows the user to determine if they are authenticated and if not send the user to the login page. See setAuthenticationEntryPoint(AuthenticationEntryPoint).
HttpServletRequest.login(String, String) - Allows the user to authenticate using the AuthenticationManager. See setAuthenticationManager(AuthenticationManager).
HttpServletRequest.logout() - Allows the user to logout using the LogoutHandlers configured in Spring Security. See setLogoutHandlers(List).
AsyncContext.start(Runnable) - Automatically copy the SecurityContext from the SecurityContextHolder found on the Thread that invoked AsyncContext.start(Runnable) to the Thread that processes the Runnable.
Detects that a user has been authenticated since the start of the request and, if they have, calls the configured SessionAuthenticationStrategy to perform any session-related activity such as activating session-fixation protection mechanisms or checking for multiple concurrent logins.
Handles any AccessDeniedException and AuthenticationException thrown within the filter chain. This filter is necessary because it provides the bridge between Java exceptions and HTTP responses. It is solely concerned with maintaining the user interface. This filter does not do any actual security enforcement. If an AuthenticationException is detected, the filter will launch the authenticationEntryPoint. This allows common handling of authentication failures originating from any subclass of org.springframework.security.access.intercept.AbstractSecurityInterceptor. If an AccessDeniedException is detected, the filter will determine whether or not the user is an anonymous user. If they are an anonymous user, the authenticationEntryPoint will be launched. If they are not an anonymous user, the filter will delegate to the AccessDeniedHandler. By default the filter will use AccessDeniedHandlerImpl. To use this filter, it is necessary to specify the following properties:
authenticationEntryPoint indicates the handler that should commence the authentication process if an AuthenticationException is detected. Note that this may also switch the current protocol from http to https for an SSL login.
requestCache determines the strategy used to save a request during the authentication process in order that it may be retrieved and reused once the user has authenticated. The default implementation is HttpSessionRequestCache.
Performs security handling of HTTP resources via a filter implementation. The SecurityMetadataSource required by this security interceptor is of type FilterInvocationSecurityMetadataSource. Refer to AbstractSecurityInterceptor for details on the workflow.
Performs actual authentication. The implementation should do one of the following: -Return a populated authentication token for the authenticated user, indicating successful authentication -Return null, indicating that the authentication process is still in progress. Before returning, the implementation should perform any additional work required to complete the process. -Throw an AuthenticationException if the authentication process fails
翻译
执行实际身份验证。 实施应执行以下操作之一:
为经过身份验证的用户返回填充的身份验证令牌,表示身份验证成功
返回null,表示身份验证过程仍在进行中。在返回之前,实施应执行完成流程所需的任何额外工作。
如果身份验证过程失败,则引发AuthenticationException
successfulAuthentication方法
Default behaviour for successful authentication:
Sets the successful Authentication object on the SecurityContextHolder
Informs the configured RememberMeServices of the successful login
Fires an InteractiveAuthenticationSuccessEvent via the configured ApplicationEventPublisher
Delegates additional behaviour to the AuthenticationSuccessHandler. Subclasses can override this method to continue the FilterChain after successful authentication.
Default behaviour for unsuccessful authentication: Clears the SecurityContextHolder Stores the exception in the session (if it exists or allowSesssionCreation is set to true) Informs the configured RememberMeServices of the failed login Delegates additional behaviour to the AuthenticationFailureHandler.
Locates the user based on the username. In the actual implementation, the search may possibly be case sensitive, or case insensitive depending on how the implementation instance is configured. In this case, the UserDetails object that comes back may have a username that is of a different case than what was actually requested..
Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or greater hash combined with an 8-byte or greater randomly generated salt.
Verify the encoded password obtained from storage matches the submitted raw password after it too is encoded. Returns true if the passwords match, false if they do not. The stored password itself is never decoded.
@PreAuthorize("hasAnyRole('worker','boss')") @PreAuthorize("hasRole('worker') AND hasRole('boss')")
@PostAuthorize: 先开在启动类开启 @EnableGlobalMethodSecurity(prePostEnabled=true),在方法执行后再进行权限验证, 适合验证带有返回值的权限, Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject, 提供了基于表达式的访问控制 例如