In the integration of Springsecurity encountered several problems, automatic configuration login, offline, logout user operation, data based on MyBatis, template engine with Thymeleaf+bootstrap.
First, the Authentication password encryption (Passwordencoder) principle is as follows
- where Md5util is the custom password encryption tool class, write casually (note add salt value), note: Understanding the process of matching passwords
//Certifications@Overrideprotected voidConfigure (Authenticationmanagerbuilder auth)throwsException {auth.userdetailsservice (Userdetailsservice ()). Passwordencoder (NewPasswordencoder () {@Override Public Booleanmatches (charsequence Rawpassword, String encodedpassword) {//match ================= The password for the user form login and Encodedpasswor (this value is encapsulated from Myuserdetailservice)) Compare ================= returnencodedpassword.equals (Encode (Rawpassword)); } @Override PublicString encode (charsequence rawpassword) {returnMd5util.encode ((String) rawpassword); } }); }
- Myuserdetailservice is an implementation of the Userdetailsservice (Springsecurity itself interface) method, where the implementation of authentication data query and login user Rights query encapsulation.
- Note: Understand the empowerment, that is, the current user here has all the roles encapsulated in the user of the springsecurity itself, but there is no authentication success, simple encapsulation only
@Service Public classMyuserdetailserviceImplementsUserdetailsservice {@Autowired userservice userservice; @AutowiredPrivateSessionregistry Sessionregistry; @Override Publicuserdetails Loaduserbyusername (String username) {if(username==NULL|| Username.equals ("")) { Throw NewUsernamenotfoundexception ("User name does not exist"); } sys_user User=Userservice.getuserbyname (username); //get information for all logged-in userslist<object> list =sessionregistry.getallprincipals (); for(Object object:list) {if((User) object). GetUserName (). Equals (User.getusername ())) {Throw NewSessionauthenticationexception ("The current user is online, login failed"); } System.out.println ("Traversal of getallprincipals" +( User) object). GetUserName ()); } //get information about the current logged-on userList<simplegrantedauthority> authorities =NewArraylist<>(); for(Role role:user.getRoles ()) {//The resulting role is encapsulated in the following page after the certificate is successfully usedAuthorities.add (Newsimplegrantedauthority (Role.getrolename ())); System.out.println ("Owned role:" +role.getrolename ()); } return NewUser (User.getusername (), User.getpassword (), authorities); }}
View Code
II. configuration of the management of the session at the time of Authorization (Configure (httpsecurity http))
- This can be said to be the core, the first turn on the automatic configuration of the logout function (focus on the default is to open otherwise the logout page), Logouturl: The custom logout URL, log out of the successful page can also be customized, here is not written, in the controller layer to implement their own definition of
// turn on the logout feature for automatic configuration. http.logout (). Permitall (); logouturl ("/logout"). Logoutsuccessurl ("/"); // indicates that the logout succeeds to the homepage // Session Management . Sessionmanagement () . Maximumsessions (1). Maxsessionspreventslogin (true) . Sessionregistry (Getsessionregistry ());
- Http.sessionmanagement (). Invalidsessionurl ("/login") sends a request with a SessionID user that is not expired but is completely invalid and is also redirected to a specific URL
Http.sessionmanagement (). Maximumsessions (1). Maxsessionspreventslogin (true)
- Maximumlogins must be-1 to allow unrestricted login, or a positive integer to specify the maximum value
- . Maximumsessions (1) Set a user to allow the number of logins Maxsessionspreventslogin enable exceeding the error.
After the measurement, the maximum number of logins is set +1, such as setting number 2, the maximum access is 3 and the fourth time error is started.
Thus, if we use this configuration to specify the user single login is not possible
Http.sessionmanagement (). Sessionfixation (). Migratesession () Spring security prevent tampering session
Iii.. Custom logoff, offline implementation (emphasis)
- The first implementation of the simple offline, temporarily set the session to invalid, did not remove (see the Source section)
if (invalidatehttpsession) {//part of source code = Request.getsession (false); if NULL { logger.debug ("invalidating session:" + Session.getid ()); Session.invalidate (); } }
@RequestMapping ("/logout") PublicString Logout (httpservletrequest request,httpservletresponse response) {/*** The first way to simply offline is not logged off user is SessionID still in **/ //get information about a logged off userAuthentication auth=Securitycontextholder.getcontext (). Getauthentication (); if(Auth! =NULL){ //set to offline status NewSecuritycontextlogouthandler (). Logout (Request, response, Auth); } return"Redirect:/login"; }
- The second completely removes SessionID from the sessionregistry, enabling user logoff
@RequestMapping ("/logout") PublicString Logout2 () {/*** The second will get the logged-on user information after the user SessionID to invalid and then removed from the sessionregistry * This way you can completely log off the user login status*/List<Object> plist=sessionregistry.getallprincipals (); List<SessionInformation> Sessionsinfo =NULL; for(Object principle:plist) {sessionsinfo=sessionregistry.getallsessions (principle,false); } System.out.println ("Number of sesssion" +sessionsinfo.size ()); for(sessioninformation sessioninformation:sessionsinfo) {//Get current SessionIDSystem.out.println ("SESSIONID:" +Sessioninformation.getsessionid ()); Sessioninformation.expirenow ();//invalidates the session and then removes it in the next stepsessionregistry.removesessioninformation (Sessioninformation.getsessionid ()); } return"Redirect:/login"; }
Iv. Source Code
Source code implementation Private messages I
Springboot Integration springsecurity Problems encountered