Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring Security

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to use Spring Security". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to use Spring Security" can help you solve the problem.

Spring Security is a powerful and highly customizable authentication and access control framework, which provides a complete authentication mechanism and method-level authorization functions. Is a very excellent rights management framework. Its core is a set of filter chains, different functions through different filters.

1. Introduce dependency

Introduce the Spring Security dependency into the project as follows:

Org.springframework.boot spring-boot-starter-security

After introducing dependencies, the entire project is protected by Spring Security, and all interfaces have to be logged in before they can be accessed. For example, I need to access the / doc.html interface documentation and jump directly to the login page. As shown below:

At this point, you will have a hundred thousand why? Where is this page from? What is this user name and password? Wait. Don't worry, listen to me one by one.

two。 Where to set the user name and password

When we introduce the Spring Secruity dependency, after starting the project, the password will be output in the console in the format of UUID, each time the startup password is different, and the user name is User by default.

Using generated security password: 8b2d752b-8892-4cd3-a7a9-a36e79e1cad8

We can customize the user name and password through the project configuration file, as follows, so that the user name and password are fixed each time the project is restarted.

Detailed explanation of spring: security: user: name: didiplus password: didiplus3.UserDetailsService API

The only abstract method for the UserDetailsService interface is loadUserByUsername (String username). The code is as follows:

Public interface UserDetailsService {UserDetails loadUserByUsername (String username) throws UsernameNotFoundException;}

The return value of the UserDetailsService interface is the UserDetails interface, which is another interface, and the Spring Security framework provides the User class object under its implementation class org.springframework.security.core.userdetails package. The userdetails source code is as follows:

Spring Security provides three implementation classes for the UserDetailsService interface, which are CachingUserDetailsService,JdbcDaoImpl,InMemoryUserDetailsManager

3.1JdbcDaoImpl implementation class

The implementation class obtains the user name and password from the database. A large number of SQL statements are defined in JdbcUserDetailsManager, as follows:

Then let's take a look at the loadUsersByUsername method in JdbcDaoImpl, as follows:

3.2InMemoryUserDetailsManager implementation class

The above code determines whether there is a User object corresponding to user data in the HashMap collection in memory. If not, an exception is thrown directly, and if so, the User object information of the user is returned.

The above code reads the User-related information in the configuration file. Through the analysis of the source code, it is found that the core of the Spring Security framework to complete the user login authentication is the UserDetailsService interface with the org.springframework.security.core.userdetails package.

3.3 Custom implementation classes implement the UserDetailsService interface

Custom implementation class MyUserDetailsServiceImpl, the code is as follows:

@ Servicepublic class MyUserDetailsServiceImpl implements UserDetailsService {private static final String USERNAME= "admin"; private static final String PASSWORD= "admin123"; @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {if (! USERNAME.equals (username)) {throw new UsernameNotFoundException ("username does not exist");} UserDetails userDetails = new User (USERNAME,PASSWORD, AuthorityUtils.commaSeparatedStringToAuthorityList ("admin,common")); return userDetails;}}

Restart the project, enter the defined user name and password, and find that you cannot log in. Check the console and find an error. The prompt is as follows:

The reason for the error is that we did not use any PasswordEncoder, and the password we entered was not encrypted with an encryption tool. Spring Security has actually provided us with a lot of PasswordEncoder. There is a PasswordEncoder interface under the org.springframework.security.crypto.password package. Look at its implementation class.

Inject the Bean of any implementation class of this PasswordEncoder that we need to encrypt passwords into the container and use it directly. The code is as follows:

@ Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {@ Bean public BCryptPasswordEncoder bCryptPasswordEncoder () {return new BCryptPasswordEncoder ();}}

Modify the MyUserDetailsServiceImpl class as follows:

@ Servicepublic class MyUserDetailsServiceImpl implements UserDetailsService {private static final String USERNAME= "admin"; private static final String PASSWORD= "admin123"; @ Resource BCryptPasswordEncoder cryptPasswordEncoder; @ Override public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {if (! USERNAME.equals (username)) {throw new UsernameNotFoundException ("user name does not exist");} UserDetails userDetails = new User (USERNAME,cryptPasswordEncoder.encode (PASSWORD), AuthorityUtils.commaSeparatedStringToAuthorityList ("admin,common")); return userDetails }}

Restart the project to test again and enter the defined account number and password. You can access the interface documentation page.

4. How to modify the login page

I think the default login page is ugly. How do we define our own login page? The method is also very simple, first of all, let's prepare a login page. As follows:

The front-end code is as follows:

Log in to Don't have account? Sign up

Store the login page file in the static directory in the project's resource folder, and then rewrite the configure (HttpSecurity http) method in SecurityConfig, as follows:

@ Override protected void configure (HttpSecurity http) throws Exception {http.formLogin () .loginPage ("/ login.html") # Custom login page .usernameParameter ("user") # corresponds to the front end expression name property. PasswordParameter ("pass") # corresponds to the front end expression name property .loginProcessingUrl ("/ login") .defaultSuccessUrl ("/ doc.html") # the address of the page that jumps after a successful login .failureUrl ("/ login?error=true") .and () .authorizeRequests () .antMatrices ("/ login.html"). PermitAll () # Open the login page .anyRequest (). Authenticated () # other requests should be authenticated by http.csrf () .disable ();}

Restart the project, enter the defined user name and password, and successfully log in and jump directly to / doc.html.

AntMatchers ("url"). PermitAll () is to let a url pass and can be accessed without logging in.

This is the end of the introduction to "how to use Spring Security". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report