Spring Boot integrates spring Security

Source: Internet
Author: User

Spring Boot for the family framework support good, but I as a small white configuration or a little bit of a small problem, here to share. This project was re-retrofitted using the previously released Spring boot Membership management system to change the previous filter login verification to spring Security
  

1. Configure Dependencies

The Spring boot framework consolidates spring security only by adding the appropriate dependencies, followed by the configuration of spring security.
The use of MAVEN development here depends on the following:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-security</artifactId></dependency>
2. Configure Spring Security 2.1 Custom Websecurityconfigureradapter

The following Java configuration of spring security does not intercept static resources and requires login verification and other information

@EnableWebSecurity@EnableGlobalMethodSecurity(prepostenabled =true)//Authentication on the Open method Public classSecurityconfigextendsWebsecurityconfigureradapter {@Resource    PrivateCustomeruserdetailsservice Userdetailsservice;@Resource    PrivateCustomerloginsuccesshandler Successhandler;@Resource    PrivateBcryptpasswordencoder encoder;@Bean     PublicBcryptpasswordencoderEncoder() {return New Bcryptpasswordencoder(); }@Override     Public void Configure(Websecurity web)throwsException {web.ignoring().antmatchers("/assets/**");//Do not filter static resources        Super.Configure(web); }@Override    protected void Configure(Authenticationmanagerbuilder auth)throwsException {auth.Userdetailsservice(Userdetailsservice)//Register your own custom-made Userdetailsservice.Passwordencoder(encoder);//Configure cipher dongle}@Override    protected void Configure(httpsecurity http)throwsException {http.authorizerequests()//Get authenticator for request.antmatchers("/","/error").Permitall()//access to the current configured path can be authenticated                    //access to other paths requires authentication and role permissions.anyrequest().hasanyauthority(Adminrole.G_admin.toString(), Adminrole.S_admin.toString())                    .anyrequest().Authenticated()                    . and()                .Formlogin()//Get login Authentication Authenticator.LoginPage("/login")//Register the custom login page URL.Failureforwardurl("/login")//Login failed to forward to the link at logon request.Successhandler(Successhandler)//The processor is called after successful login.Permitall()//Login request to pass authentication. and()                .Logout()//Launch login.Logoutsuccessurl("/login")//exit after access URL. and()                .CSRF().Disable();//Turn off CSRF, turn on by default}}

The above class is for configuring the Spring security framework, here are a few things to illustrate below:

    • @EnableGlobalMethodSecurity
      This is used to configure the class/method of security authentication, it is closed by default, we have now configured @EnableGlobalMethodSecurity(prePostEnabled = true) this will make it possible to use annotations on the method @PreAuthorize("hasAnyAuthority(‘S_ADMIN‘)") (using the example can be seen AdminController ) when the method is not called annotations to determine whether the current authentication user has s_admin The role permission operation for this method.
      This annotation can make a difference when developing a non-Web project.

    • Configure (Authenticationmanagerbuilder auth)
      Here you can configure the project's association with the user, also known as authentication. We need to build our own login authenticator, where we have customized one UserDetailsService and one cipher encryption device.

    • Configure (Httpsecurity http)
      Here we can configure what kind of security authentication we need for a httpsecurity. The code is also included csrf().disable() , because the framework defaults on CSRF, so that our Ajax and form submissions need to provide one token , in order to be lazy, so, you know

There is a small tip, which is a configuration, equivalent to xml,spring only load once, so the above method spring is initialized once

2.2 Custom Userdetailsservice

In the above we registered a custom UserDetailsService , this is used when the user authentication we need to provide a framework can be identified UserDetails , with this UserDetails and our login user entity class to establish an association, so that the framework can process our user information, the framework provides just username and password, it just helps us to verify that our users and passwords match. The custom UserDetailsService code is as follows:

@Component //Register as Spring component Public classCustomeruserdetailsserviceImplementsuserdetailsservice{@Resource    PrivateAdmindao Admindao;@Override     PublicUserdetailsLoaduserbyusername(String username)throwsusernamenotfoundexception {//Find the user with the current user name through DAOAdmin admin = Admindao.Findadminbyusername(username);if(Admin = =NULL){Throw New usernamenotfoundexception("This username:"+username+"is not exist"); }//Return to a custom userdetails        //authorityutils.createauthoritylist (Admin.getrole ()) is to generate a collection of all the permissions (roles) of the user        return New customeruserdetails(Admin, Authorityutils.createauthoritylist(admin.Getrole())); }}

When we log in, the org.springframework.security.authentication.dao.DaoAuthenticationProvider method is called loadUserByUsername and the user name that is currently required for authentication is passed in, and all we need is to put back a password information that is derived from that user name, UserDetails so that the framework can help us verify that the password that needs authentication matches the password that was identified.

2.3 Custom Userdetails

In order for spring security to recognize what we have customized, it needs to be UserDetails written according to its standards, so we need to implement an UserDetails interface with the following code:

 Public classCustomeruserdetailsImplementsuserdetails {PrivateAdmin admin =NULL;//Set of storage permissions    Private Finalcollection<?extendsGrantedauthority> authorities;Private Final Booleanaccountnonexpired;Private Final Booleanaccountnonlocked;Private Final Booleancredentialsnonexpired;Private Final BooleanEnabled Public customeruserdetails(admin admin, collection<?extendsGrantedauthority> authorities) { This(Admin,true,true,true,true, authorities); } Public customeruserdetails(admin admin,BooleanEnabledBooleanAccountnonexpired,BooleanCredentialsnonexpired,BooleanAccountnonlocked, collection<?extendsGrantedauthority> authorities) {if(admin.GetUserName() !=NULL&&!"".equals(admin.GetUserName()) && Admin.GetPassword() !=NULL) { This.Admin= admin; This.enabled= enabled; This.accountnonexpired= accountnonexpired; This.credentialsnonexpired= credentialsnonexpired; This.accountnonlocked= accountnonlocked; This.authorities= authorities; }Else{Throw NewIllegalArgumentException ("cannot pass null or empty values to constructor"); }    } PublicAdminGetadmin() {returnAdmin } Public void Setadmin(@NotNullAdmin admin) { This.Admin= admin; } Public Boolean equals(Object RHS) {returnRhsinstanceofCustomeruserdetails && This.GetUserName().equals(((customeruserdetails) RHS).GetUserName()); } Public int hashcode() {return  This.GetUserName().hashcode(); }@Override     Publiccollection<?extendsGrantedauthority>getauthorities() {return  This.authorities; }@Override     PublicStringGetPassword() {return  This.Admin.GetPassword(); }@Override     PublicStringGetUserName() {return  This.Admin.GetUserName(); }@Override     Public Boolean isaccountnonexpired() {return  This.accountnonexpired; }@Override     Public Boolean isaccountnonlocked() {return  This.accountnonlocked; }@Override     Public Boolean iscredentialsnonexpired() {return  This.credentialsnonexpired; }@Override     Public Boolean isenabled() {return  This.enabled; }}

The above is written according to the user class provided by spring security to rewrite, the specific code can see the org.springframework.security.core.userdetails.User source.
In the org.springframework.security.core.userdetails.User rewrite hashCode and equals may be to judge the problem of repeated logins, of course, this is only a personal fantasy, purely blind guessing. For the sake of safety I also followed the two methods of rewriting.
In customizing UserDetails I added a member variable admin , this is because the previous development did not use the framework, just use filter login authentication, the login information is stored to session , so, in order not to change the old things before, so I will also get from here to admin save insession

2.4 Custom Authenticationsuccesshandler

Customization AuthenticationSuccessHandler does not directly inherit the interface, but instead inherits an implementation class SavedRequestAwareAuthenticationSuccessHandler , because this saves our pre-logon request information, and we can implement the URL to redirect RequestCache directly from the login page to the pre-logon access without having to obtain the following code:

@Component Public classCustomerloginsuccesshandlerextendsSavedrequestawareauthenticationsuccesshandler {@Override     Public void onauthenticationsuccess(HttpServletRequest request, httpservletresponse response, authentication authentication)throwsIOException, Servletexception {//securitycontextholder is the core component of spring security and gets some of the information within the framework love        //Here I get login successful after the UserdetailsObject principal = Securitycontextholder.GetContext().getauthentication().Getprincipal();if(PrincipalinstanceofUserdetails) {request.getsession().SetAttribute("Admin", ((customeruserdetails) principal).Getadmin()); }Super.onauthenticationsuccess(Request, response, authentication); }}

For the framework core components in the code above, you can view this link in the official documentation
The main purpose of customizing this processor is because I want to be lazy because my template engine needs access admin to get the username, and of course it can be used ${session.SPRING_SECURITY_CONTEXT.authentication.principal.username} to get UserDetails the user name

3. Summary

This is almost the end of writing here, I will do a personal summary. This integration spring security Midway is not like this article so down, in the middle of a bump, so, I was thinking, is not I just stay in the application layer to lead to such a result, if the source of more than a bit of understanding of the problem may not occur.

The above code has been uploaded to GitHub

Refer to Links
https://docs.spring.io/spring-security/site/docs/5.0.3.RELEASE/reference/htmlsingle/
55803855
http://www.tianshouzhi.com/api/tutorials/spring_security_4/250

Spring Boot integrates spring Security

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.