Spring Boot Series--spring security (database-based) login and permission control

Source: Internet
Author: User

Let's talk first. Authconfig.java one of the main configuration files for Spring security authconfig

 1 @Configuration 2 @EnableWebSecurity 3 public class Authconfig extends Websecurityconfigureradapter {4 @Override 5         protected void Configure (Httpsecurity httpsecurity) throws Exception {6 httpsecurity.authorizerequests () 7 . Antmatchers ("/css/**", "/staic/**", "/js/**", "/images/**"). Permitall () 8. Antmatchers ("/", "/login", "/sessio N_expired "). Permitall () 9. Formlogin (), LoginPage ("/login "). Defaultsuccessur L ("/main_menu") Failureurl ("/loginerror"), Usernameparameter ("Txtusercd"). Passwordparamete R ("Txtuserpwd") Permitall (). Logout (). Logoutrequestmatcher (New Antpathreq Uestmatcher ("/logout")). Logoutsuccessurl ("/"). Deletecookies ("Jsessionid"). Invalidatehttps Ession (True) Permitall (), Sessionmanagement (). Invalidsessionurl ("/session _expired "). MaXimumsessions (1) Maxsessionspreventslogin (true) expiredurl ("/session_expired"); Ty.logout (). Permitall ()}33 @Autowired35 authuserservice authuserservice;36 public void Glo       Balauthconfig (Authenticationmanagerbuilder auth) throws Exception {Notoginseng auth.userdetailsservice (authuserservice); 38 Auth.inmemoryauthentication (). Withuser ("user"). Password ("password");}40/* @Configuration41 protecte         D static Class Authenticationconfiguration extends Globalauthenticationconfigureradapter {@Autowired43 Authuserservice authuserservice;44 @Override46 public void init (Authenticationmanagerbuilder auth) Throws Exception {//auth.inmemoryauthentication (). Withuser ("user"). Password ("password"); auth . Userdetailsservice (Authuserservice); 49}50}*/51}

First, Configur method basic Configuration

No Source Comment
L1 @Configuration This is the Java form of the Bean spring3.0 later allows @Configuration annotations to replace the XML form of the Bean
L2 @EnableWebSecurity Use this annotation to turn on spring Security configuration verification on
L3 Websecurityconfigureradapter This requires us to inherit the Websecurityconfigureradapter adapter and rewrite

Configure function to implement access control (what permissions are required for those access/resources) and login validation (database validation/memory validation)

L6 Authorizerequests () Complete the Access/authorization configuration by Authorizerequests () with a sub-function
l7,8 Antmatchers/permitall The resources configured in the Antmatchers are accessible to all users (Permitall)
L9 and () Similar to end tag
L10 Formlogin Configure the login form with the function of the Formlogin ()
L11 LoginPage Set the login page
L12 Defaultsuccessurl Default Login Success Jump Address
L13 Failureurl Default Logon Failure jump address
l14,15 Usernameparameter
Passwordparameter
User name Password verification * Here are the parameters to be consistent with the name of the controls on the screen
L18 Logout () To configure logoff with a function that is logout ()
L19 . Logoutrequestmatcher (New Antpathrequestmatcher ("/logout")) Set the request URL for logoff
L20 Logoutsuccessurl Set the jump URL after successful logoff
L21 Deletecookies Eliminate cookies
L22 Invalidatehttpsession Destroy session
L25 Sessionmanagement Configure the session with the function of the sessionmanagement
L27 Maximumsessions The same user session upper limit setting * is more than one user logged in
L28 Maxsessionspreventslogin Maximumsessions set upper Limit enabled * out of error
L29 Expiredurl

Exceed session limit Jump URL setting

Second, Globalauthconfig method certification

First say L38 this line is the memory authentication mode means that a user named password is created.

And then L37, which is also the certification core.

Let's take a look at the composition of this incoming parameter, which is the Authuserservice class

1 @Service 2 public class Authuserservice implements userdetailsservice{3  4     @Autowired 5     Mstusersmapper Mstusersmapper; 6      7     @Override 8 public     userdetails Loaduserbyusername (String username) throws Usernamenotfoundexception { 9         users Users =mstusersmapper.selectbyprimarykey (username),         if (Users = = null) {One             throw new Usernamenotfoundexception ("User not found for name:" +username);         }13         return new Authuser (users);     Public     String Getauthoritybyloginid (String loginId) {         //map<string,string> Authkindmap = new hashmap<string,string> ();         String auth = Mstusersmapper.selectauthoritybyloginid (loginId); 19         return auth;20     } 21}

You can see that we implemented the Userdetailsservice and then rewritten a loaduserbyusername and appended a Getauthoritybyloginid function

About Getauthoritybyloginid is basically the right of the current user

And then the Loaduserbyusername.

You can basically see through the name of the user through the name of the information is actually the case here does not judge you lose the password is mainly

Determine the user name you entered in the database does not exist there is no error thrown out the existence of the instantiation of a authuser return

This Authuser class is also very important to implement the userdetails as follows

 1 public class Authuser implements Userdetails {2 private static final long serialversionuid = 1L; 3 4 Priv Ate String userId; 5 Private String LoginId; 6 private String password; 7 Private String Authoritykind; 8 Public Authuser (users users) {9 super (); This.userid = Users.getuserid (); This.loginid = Users.getloginid (); This.password = Users.getpassword (); this.authoritykind = Users.getauthoritykind ();}15 @Override17 public collection<grantedauthority> getauthorities () {List<grante dauthority> list = new arraylist<grantedauthority> (), List.add (New Simplegrantedauthority (AuthorityKind     ); return list;21}22 @Override24 public String GetPassword () {return password;26 }27 @Override29 public String getusername () {return loginid;31}32 @Override34 publi C Boolean isaccountnonexpired () {return true;36}37 @Override39 public boolean isaccountnonlocked () {return true;41 }42 @Override44 Public boolean iscredentialsnonexpired () {return true;46}47 @Overri De49 public boolean isenabled () {true;51}

Here are a few points to note

L17 getauthorities It returns a collection of permissions that echoes the function you use on the screen side of the hasanyauthority (' Role_user ', ' role_admin ')

In other words, you can write on the picture side as well because you're here. Set the permissions of the current user in the

Then take a look at the information we've implemented for Userdetails, the parent class, such as the Xia Guan Web document.

No Modifier and Type Method and Description
1 java.util.Collection<? extends GrantedAuthority> getAuthorities()Returns the authorities granted to the user.
2 java.lang.String getPassword()Returns the password used to authenticate the user.
3 java.lang.String getUsername()Returns the username used to authenticate the user.
4 boolean isAccountNonExpired()Indicates whether the user's account has expired.
5 boolean isAccountNonLocked()Indicates whether the user is locked or unlocked.
6 boolean isCredentialsNonExpired()Indicates whether the user ' s credentials (password) has expired.
7 boolean isEnabled()Indicates whether the user is enabled or disabled.

The top 3 should be needless to say, start with the fourth one.

Isaccountnonexpired (): Whether the current account has expired

Isaccountnonlocked (): Whether the current account is locked

Iscredentialsnonexpired (): Current account certificate (password) expired

IsEnabled (): Whether the current account is disabled

Set it to true otherwise the login will be reported

There are also implementations of a Userdetailsservice class as follows

1 @Service 2 public class Authuserservice implements userdetailsservice{3  4     @Autowired 5     Mstusersmapper Mstusersmapper; 6      7     @Override 8 public     userdetails Loaduserbyusername (String username) throws Usernamenotfoundexception { 9         users Users =mstusersmapper.selectbyprimarykey (username),         if (Users = = null) {One             throw new Usernamenotfoundexception ("User not found for name:" +username);         }13         return new Authuser (users);     Public     String Getauthoritybyloginid (String loginId) {         //map<string,string> Authkindmap = new hashmap<string,string> ();         String auth = Mstusersmapper.selectauthoritybyloginid (loginId); 19         return auth;20     } 21}
If you see that loaduserbyusername this function does not do password verification just take username to fetch user information, of course, can not get an error
Take it to Authuser, then spring boot himself to judge the password, and the previous check
That's all that's left of the controller, and there's nothing special to say to Git.
Finally, paste the execution and git address

Finish

Spring Boot Series--spring security (database-based) login and permission control

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.