Spring security can run in different authentication environments, and when we recommend that users use spring security for authentication but do not recommend integration into container-managed identity authentication, it is still supported when you integrate into your own identity authentication system.
1. What is the identity authentication in Spring security?
Now let's consider a standard authentication scenario that everyone is familiar with:
(1) The user intends to log into the system using username and password
(2) System authentication user name and password legal
(3) The context (role, etc.) of the user's information
(4) Establish a security context for the user
(5) The user may then perform a protected operation under a privileged access mechanism to check the required permissions in relation to the current security context
The first three steps above are the process of identity authentication, and then look at the detailed process of identity authentication:
(1) An instance of Usernamepasswordauthenticationtoken after the user name and password have been obtained (an instance of the authentication interface discussed earlier)
(2) Pass the token to the AuthenticationManager instance for validation
(3) After successful verification, AuthenticationManager will return the populated authentication instance
(4) by calling Securitycontextholder.getcontext (). Setauthentication (...) to establish an instance of the security context passed on to the returned identity authentication object
Here is the code snippet for identity authentication:
import org.springframework.security.authentication.*;import org.springframework.security.core.*; import org.springframework.security.core.authority.simplegrantedauthority;import Org.springframework.security.core.context.securitycontextholder;public class authenticationexample { private static AuthenticationManager am = new Sampleauthenticationmanager (); public static void main (String[] args) throws Exception { BufferedReader in = new BufferedReader (New inputstreamreader (system.in)); while (True) { system.out.println ("Please enter your username:"); string name = in.readline (); System.out.println ("Please enter your password:"); &nbSp; string password = in.readline (); try { authentication request = new Usernamepasswordauthenticationtoken (Name, password); Authentication result = am.authenticate (Request); securitycontextholder.getcontext (). Setauthentication (Result); break; } catch (authenticationexception e) { system.out.println ("authentication failed: " + E.getmessage ()); } } System.out.println ("successfully authenticated. security context contains: " + &nbSp; securitycontextholder.getcontext (). GetAuthentication ()); }}class SampleAuthenticationManager implements AuthenticationManager { static final list<grantedauthority> authorities = new arraylist< Grantedauthority> (); static { authorities.add (new Simplegrantedauthority ("Role_user")); } public authentication Authenticate (Authentication auth) throws AuthenticationException { if (Auth.getname (). Equals (Auth.getcredentials ())) { return New usernamepasswordauthenticationtoken (Auth.getname (), Auth.getcredentials (), authorities); } throw new badcreDentialsexception ("Bad credentials"); } }
We wrote a small program that asked the user to enter a user name and password and perform the above sequence. The AuthenticationManager we implement verifies that the user name and password are consistent, and it assigns a role to each user. The above output is similar to this:
Please enter your username: Favboy Please enter your password: Favccxx Authentication failed: Bad Credentials Please enter your username: Favboy Please enter your password: Favboy Successfully authenticated. Security context contains: \ Org.springframew[email protected]441d0230: \ Principal:bob; Password: [PROTECTED]; \ Authenticated:true; Details:null; \ Granted Authorities:role_user |
Note that you usually do not need to write any code. This process typically occurs internally, such as a Web authentication filter. The above code simply tells us that it is so simple to use identity authentication in spring security. When Securitycontextholder contains a populated authentication object, the user's identity is completed.
2. Directly set the content of Securitycontextholder
In fact, Spring security doesn't care how to put authentication objects into Securitycontextholder. The only key is that Securitycontextholder needs to have authentication objects before the user operates the certified Abstractsecurityinterceptor.
For systems that are not spring security, you can write your own filters or MVC controllers to integrate with your identity authentication system. For example, you might use a container-managed authentication system to get users from threadlocal or Jndi. You may also be working in a company that has a legacy authentication system, which is the "standard" of a business, and there is nothing you can do about it. In this case, it is very easy to use spring security to provide authentication, you only need to write a filter to read third-party user information, and then build a spring security-specific authentication object, and put it in the Authenticationcontextholder. In this case, you need to consider the basic information of your own identity authentication. For example, you need to create an HTTP session to cache the context between requests before responding to the client.
3 Using identity authentication in Web Apps
Next, let's explore how to use spring security to authenticate with the Web application without the XML security policy configured, how to establish user authentication and security context?
Here is the process for Web App authentication:
(1) Visit the homepage of an application and click on a link.
(2) Send a request to the server, and the server determines whether the user is accessing the protected resource.
(3) Since the user was not previously authenticated, the server sends a response (which may be an HTTP response code or may jump directly to a Web page) to tell the user that authentication is required.
(4) The authentication mechanism determines whether the browser jumps to a specific Web page to allow the user to fill out a form form, or the browser retrieves the user's identity in some way (Basic Authentication dialog box, cookie, or A/P certificate).
(5) The browser sends a response (an HTTP POST request containing form information or an HTTP header containing the user's authentication details) back to the server.
(6) Next, the server determines whether the previous credentials are valid. If it works, the next step will be made. Otherwise, the browser will usually ask if it needs to retry.
(7) The original request will cause the identity authentication process to be restarted, re-judge that the user has sufficient access to the protected resources, if the user has permissions, the request is successful. Otherwise, an HTTP error code of 403 is returned, indicating that the user does not have permission to operate.
Spring security has specific classes that are responsible for the above steps, and the main classes are exceptiontranslationfilter , authenticationentrypoint , and calling Auenticationmanager 's "Identity authentication mechanism".
3.1 Exceptiontranslationfilter
As the name implies, Exceptiontranslationfilter is the filter that handles exceptions in spring security that are thrown by the abstractsecurityinterceptor that provide the authentication service.
3.2 Authenticationentrypoint
Step 3 above is Auenticationentrypoint's responsibility, you can imagine each Web application has a default authentication test, each major authentication system has authenticationentrypoint implementation, Usually perform one of the actions described in step 3.
3.3 identity authentication mechanism
Once your browser has submitted a verification certificate (HTTP form post or HTTP header), this requires something on the server to hold these permissions information. But now in the 6th step above, in spring security we have a specific name for the operation of verifying information for the mobile phone. From a user agent (usually a browser), reference it as a "validation mechanism." For example, a form-based login or basic validation. Once the validation details are collected from the user agent, the authentication request object is established and then submitted to AuthenticationManager.
After the authentication mechanism receives the populated authentication object, it considers the request to be legitimate, puts the authentication in Securitycontextholder, and retries the original request (7th step). On the other hand, AuthenticationManager rejects the request, and the authentication mechanism causes the user agent to retry (step 2nd).
3.4 Save SecurityContext between requests
Depending on the type of application, a policy is required to save the security context between user actions. In a typical Web application, a user login log is then determined by its session ID, and the server caches the principal information to keep session sessions. In spring security, the responsibility for storing securitycontext between requests falls on the Securitycontextpersistencefilter, by default, Securitycontextpersistencefilter stores the context on the HttpSession property in an HTTP request. The context of each request is stored on Securitycontextholder, and, most importantly, it clears securitycontextholder when the request is complete. For security reasons, the user should not directly manipulate HttpSession, there is a simple way to implement-use Securitycontextholder instead.
Many other types of applications, such as a stateless rest Web service, do not use HTTP sessions and are re-validated on each request. However, it is still important to include the securitycontextpersistencefilter in the request chain, which ensures that the securitycontextholder will be emptied after each request.
This article is from the "Dust Wind with the Sky" blog, please be sure to keep this source http://favccxx.blog.51cto.com/2890523/1606721
Spring Security's identity certification