Springsecurity Some notes after a simple use

Source: Internet
Author: User

Spring security certification is managed by AuthenticationManager, but the real certification is the Authenticationprovider defined in AuthenticationManager. Multiple authenticationprovider can be defined in AuthenticationManager. When we use the Authentication-provider element to define a authenticationprovider, if the associated Authenticationprovider object is not specified, Spring Security Daoauthenticationprovider is used by default. Daoauthenticationprovider requires a userdetailsservice to obtain the user's information userdetails when authenticating, including user name, password, and permissions. so if we need to change the way certification, we can achieve their own authenticationprovider, if we need to change the authentication of the source of user information, we can implement Userdetailsservice.

1. Implement the Userdetailsservice interface

Customuserdetailsservice class:

 Packagecn.lger.security;ImportCn.lger.dao.UserDao;ImportCn.lger.entity.User;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.security.core.authority.SimpleGrantedAuthority;Importorg.springframework.security.core.userdetails.UserDetails;ImportOrg.springframework.security.core.userdetails.UserDetailsService;Importorg.springframework.security.core.userdetails.UsernameNotFoundException;Importjava.util.ArrayList;Importjava.util.List; Public classCustomuserdetailsserviceImplementsUserdetailsservice {@AutowiredPrivateUserdao Userdao; @Override PublicUserdetails Loaduserbyusername (String username)throwsusernamenotfoundexception {User User=Userdao.findbyusername (username); if(User = =NULL){            Throw NewUsernamenotfoundexception ("Not Found"); } List<SimpleGrantedAuthority> authorities =NewArraylist<simplegrantedauthority>(); Authorities.add (Newsimplegrantedauthority (User.getrole ())); System.err.println ("Username is" + username + "," +user.getrole ()); return NewOrg.springframework.security.core.userdetails.User (User.getusername (), User.getpassword (), authorities    ); }}

Add this userdetailsservice in the Configure (Authenticationmanagerbuilder auth) method below

Securityconfig class:

 PackageCn.lger.config;ImportCn.lger.security.CustomUserDetailsService;ImportOrg.springframework.context.annotation.Bean;ImportOrg.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;Importorg.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;Importorg.springframework.security.config.annotation.web.builders.HttpSecurity;Importorg.springframework.security.config.annotation.web.configuration.EnableWebSecurity;ImportOrg.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;ImportOrg.springframework.security.core.userdetails.UserDetailsService;Importorg.springframework.security.crypto.bcrypt.bcryptpasswordencoder;@ Enablewebsecurity@enableglobalmethodsecurity (prepostenabled=true) Public classSecurityconfigextendswebsecurityconfigureradapter {@Override @Bean PublicUserdetailsservice Userdetailsservice () {return NewCustomuserdetailsservice (); } @Overrideprotected voidConfigure (Authenticationmanagerbuilder auth)throwsException {auth. Userdetailsservice (Userdetailsservice ()). Passwordencoder (/ c9>NewBcryptpasswordencoder ()); } @Overrideprotected voidConfigure (Httpsecurity http)throwsException {http. authorizerequests (). Antmatchers ("/", "/Home"). Permitall (). Antmatchers ("/css/**", "/js/**", "/img/**", "/vendors/**"). Permitall (). Anyrequest (). Permitall (). and (). Formlogin (). D Efaultsuccessurl ("/user/list"). Permitall (). and (). Logout (). Permitall (). A    nd (). CSRF (). disable (); }  }

Although this is a class to add to Authenticationmanagerbuilder this constructor class, not the real authenticationmanager, but after I have tried the breakpoint debugging, The breakpoint is entered at the start-up stage, and the debug result is as follows:

Just beginning to enter our own written security Configuration class Securityconfig's parent Class Websecurityconfigureradapter's init (final websecurity Web) This method

The location of the breakpoint calls the Gethttp () method, and then we take a look inside the method, such as:

Here's the breakpoint position I've seen authenticationmanager the construction of an object of this class, and then continue into AuthenticationManager () This method to look inside, How this AuthenticationManager object is built:

Come in and judge AuthenticationManager whether the class has already initialized an object, and if it initializes it returns the AuthenticationManager object directly, otherwise it calls configure ( Authenticationmanagerbuilder auth) This method, because Securityconfig this class overrides websecurityconfigureradapter this class originally configure ( Authenticationmanagerbuilder auth) This method, so running to the next breakpoint will go to the Securityconfig class of configure (Authenticationmanagerbuilder auth) Method:

This gives it a userdetailsservice instance before building an instance of the AuthenticationManager class, so that Daoauthenticationprovider It is possible to get an instance of Userdetails through the Loaduserbyusername (String username) in this instance, which we implement ourselves, and I have experimented with this loaduserbyusername ( String username) method will play a role when we login authentication, if we log in successfully will return a Userdetails instance, this Userdetails instance contains the user's user name, password and permissions (the permission is a set, Description can support multiple roles for one user)

Springsecurity Some notes after a simple use

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.