1 Spirngboot Environment Construction
Create a Springboot project, see the three less relevant blog posts for details
For more information, click to
Spirngboot Project Scaffolding-click to
2 Introducing spirngsecurity Dependencies
Tip 01: Once the springsecurity dependency is introduced, the project will be managed by springsecurity; The default login name is user and the login password will be printed to the console
Tip 02:springsecurity The default configuration is to use the
<!--spring-security Related-- <dependency> <groupid>org.springframework.boot</groupid > <artifactId>spring-boot-starter-security</artifactId> </dependency>
2.1 Starting the Project
Tip 01: The passwords printed on each startup project are different
The login password information printed by the console is as follows:
2.2 Request a background implementation of the RESTFULAPI
Tip 01: Once the project is started, the front desk will be redirected to a default login page when it is first accessed
Tip 02:springsecurity The default configuration when using forms to sign in
Tip 03: The front and back end is also used when the form login, and the user name of the form must be username, the password must be password (PS: The front and back of the separation only need to simulate the form submission request, that is: request path correspondence, request parameters and background corresponding can)
2.3 Entering information
Tip # 01: If the username is not user or the password is not a console-printed message, it will not be validated
Tip 02: If the login information succeeds, Springsecurity will redirect to the previously accessed path by default
Tip 03: The front-end separation requires login verification whether successful or not is to return JSON-formatted data, specifically how to jump to have the front-end to control
3 spirngsecurity Basic Configuration
Tip 01: You need to rewrite a userdetaiservice class when customizing Springsecurity, which requires a tool class that encrypts and decrypts the password, So we need to specify in the custom springsecurity configuration file The bean for this cryptographic decryption tool class, so that the class will be managed by the spring container
Package Cn.test.demo.base_demo.config.springsecurity;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.security.config.annotation.web.builders.httpsecurity;import Org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;import Org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;import Org.springframework.security.crypto.password.PasswordEncoder;/** * @author Wang Yangji * @create 2018-05-27 21:27 * @desc **/@Configurationpublic class Furyspringsecurityconfig extends Websecurityconfigureradapter {/** Dependent injection of a custom login success processor*/@Autowired private Furyauthenticationsuccesshandler Furyauthenticationsuccesshandler; /** Dependent injection of a custom login failure handler*/@Autowired private Furyauthenticationfailurehandler furyauthenticationfailurehandler;//to create a bean in a spring container@Bean public Passwordencoder Passwordencoder () {return NewBcryptpasswordencoder (); }//@Override//protected void Configure (Httpsecurity http) throws Exception {//Http.formlogin ()//. Loginprocessingurl ("/login")//. Successhandler (Furyauthenticationsuccesshandler)//. Failurehandler (Furyauthenticationfailurehandler)//. and (). Authorizerequests ()//. Antmatchers ("/login"). Permitall ()//. Anyrequest ()//. Authenticated ()//. and (). CSRF (). disable ();// }}
View Code
For more information, click to
4 Inheritance Userdetaiservice
Inheriting Userdetaiservice subclasses can implement login user authentication and login user's permission query
Package Cn.test.demo.base_demo.config.springsecurity;import Lombok.extern.slf4j.slf4j;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean; Import Org.springframework.security.core.authority.authorityutils;import Org.springframework.security.core.userdetails.user;import Org.springframework.security.core.userdetails.userdetails;import Org.springframework.security.core.userdetails.userdetailsservice;import Org.springframework.security.core.userdetails.usernamenotfoundexception;import Org.springframework.security.crypto.password.passwordencoder;import org.springframework.stereotype.Component;/** * @author Wang Yangji * @create 2018-05-27 21:23 * @desc **/@Component @slf4jpublic class Furyuserdetailservice implements Userdetailsservice {/** * Dependent injection password encryption and decryption tool (PS: This bean needs to be configured in the Springsecurity configuration file)*/@Autowired private Passwordencoder passwordencoder; @Override public userdetails loaduserbyusername (String username) throws Usernamenotfoundexception {//Print the user data passed to the front end.Log.info ("The front-end user name is: {}", username); //simulating data in a databaseString pwd = Passwordencoder.encode ("111"); //returns a User object (Tip 01: The password for this user object is the password taken from the database)////Tip 02: Passwords in the database are encrypted using the same password encryption and decryption tool in the Spreingsecurity configuration as the user's password is created return NewUser (username, pwd, authorityutils.commaseparatedstringtoauthoritylist ("admin")); }}
View Code
For more information, click to
4.1 Testing
After restarting the project, when accessing a RESTFULAPI, the console will no longer print out the password information, and the subclass inheriting the Userdetaiservice will receive the user name and password passed to the front end. We can rely on the inherited Userdetaiservice subclass of the injection-first-close persistence layer to the user name to the database to query the user's password, the password to be found and the user login password to compare, so as to determine whether the user login verification success You can also query the user's permission information based on the user name in the database.
Tip 01: User name can be entered at random
Tip 02: Because the password is three less hard-coded in the background, so the password must be logged in "111" (That is: Any user name, password as long as 111 can log on successfully, otherwise it will fail to log in)
6 Front-End separation configuration
For more information, click to
Requirement 01: Modify the login path of the form
"To configure the login request path
Requirement 01: Returns the JSON format string regardless of whether the login verification is successful or not
Tip 01: The above requirements can be implemented in the custom springsecurity configuration
Tip 02: When the front and back ends are detached, the request must be in the post mode and must pass the username and password two variables to the background
6.1 Validated JSON format returned
You only need to implement two processing interfaces separately: Authenticationsuccesshandler, Authenticationfailurehandler; The two interfaces handle the success and failure of login verification respectively
Package Cn.test.demo.base_demo.config.springsecurity;import Com.fasterxml.jackson.databind.ObjectMapper; Import Lombok.extern.slf4j.slf4j;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.security.core.authentication;import Org.springframework.security.web.authentication.authenticationsuccesshandler;import Org.springframework.stereotype.component;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import java.io.IOException;/** * @author Wang Yangji * @create 2018-05-27 21:48 * @desc **/@Slf4j @componentpublic class Furyauthenticationsuccesshandler implements Authenticationsuccesshandler {@ autowired private Objectmapper Objectmapper; //JSON conversion Tool@Override Publicvoidonauthenticationsuccess (httpservletrequest request, httpservletresponse response, authentication authentication ) throws IOException, servletexception {log.info ("Login Verification Succeeded"); Response.setcontenttype ("Application/json;charset=utf-8");//Response TypeResponse.getwriter (). Write (objectmapper.writevalueasstring ("Login Verification succeeded")); }}
Furyauthenticationsuccesshandler.java
Package Cn.test.demo.base_demo.config.springsecurity;import Com.fasterxml.jackson.databind.ObjectMapper; Import Lombok.extern.slf4j.slf4j;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.security.core.authenticationexception;import Org.springframework.security.web.authentication.authenticationfailurehandler;import Org.springframework.stereotype.component;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import java.io.IOException;/** * @author Wang Yangji * @create 2018-05-27 21:55 * @desc **/@Component @slf4jpublic class Furyauthenticationfailurehandler implements Authenticationfailurehandler {@ autowired private Objectmapper Objectmapper; @Override Publicvoidonauthenticationfailure (httpservletrequest request, httpservletresponse response, Authenticationexception Exception) throws IOException, servletexception {log.info ("Login Verification Failed"); Response.setcontenttype ("Application/json;charset=utf-8"); Response.getwriter (). Write (objectmapper.writevalueasstring (exception));; }}
Furyauthenticationfailurehandler.java6.2 Configuring the Custom springsecurity configuration
Package Cn.test.demo.base_demo.config.springsecurity;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.security.config.annotation.web.builders.httpsecurity;import Org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter;import Org.springframework.security.crypto.bcrypt.bcryptpasswordencoder;import Org.springframework.security.crypto.password.PasswordEncoder;/** * @author Wang Yangji * @create 2018-05-27 21:27 * @desc **/@Configurationpublic class Furyspringsecurityconfig extends Websecurityconfigureradapter {/** Dependent injection of a custom login success processor*/@Autowired private Furyauthenticationsuccesshandler Furyauthenticationsuccesshandler; /** Dependent injection of a custom login failure handler*/@Autowired private Furyauthenticationfailurehandler furyauthenticationfailurehandler;//to create a bean in a spring container@Bean public Passwordencoder Passwordencoder () {return NewBcryptpasswordencoder (); } @Override protectedvoidConfigure (Httpsecurity http) throws Exception {Http.formlogin (). Loginprocessingurl ("/furylogin")//Logon Request Path. Successhandler (Furyauthenticationsuccesshandler)//Verify successful processor. Failurehandler (Furyauthenticationfailurehandler)//validation failed processor. and (). Authorizerequests (). Antmatchers ("/furylogin"). Permitall ()//the logon request path is not filtered. Anyrequest (). authenticated (). and (). CSRF (). disable (); //eliminate cross-site request forgery Protection }}
View Code
6.3 Testing
Testing with the Postman
Tip 01: Just simulate the login request, the POST request, the parameters are username and password, respectively.
Pit 01: Although the login request path configured in the springsecurity custom configuration file is/furylogin, we must simulate the http://127.0.0.1:9999/dev/furyLogin when impersonating, because the IP must be added, Port and Application Context path
6.3.1 sign-in verification failed effect show
6.3.2 Effect of Login success
Case source code, click to go
7 using angular for front-end login
8 after successful login, the corresponding menu information is returned.
9 Permissions Issues
SPRINGBOOT20 integrated SpringSecurity02, using springsecurity for front-end separation of login verification