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 customize the user login page and login processing logic in Spring security 02

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

Share

Shulou(Shulou.com)06/02 Report--

Spring security 02 how to customize the user login page and login processing logic, in response to this problem, this article details the corresponding analysis and solution, hoping to help more want to solve this problem of small partners to find a simpler and easier way.

Spring security Blog Directory

Spring Security 01-Introducing Spring security into projects

Spring security 02-Customizing user login pages and login processing logic

Spring security 03-Customizing the processing logic after successful login

Spring security 04-Integration jwt

corresponding source

Spring Security 01-Introducing Spring security into projects

Spring security 02-Customizing user login pages and login processing logic

Spring security 03-Customizing the processing logic after successful login

Spring security 04-Integration jwt

opening

previous (What happens when we introduce spring-security into the project) We introduced Spring-security into our spring-boot project. Without extra configuration, spring-security has already configured an interceptor for us by default. After the application is started, when we access the resources provided by the application, we will jump to a default landing page provided by security. When we enter the username and password provided by security for us, after logging in successfully, We can get the resources we need. So here's the problem! How do we customize our login page and log in using our own user information?

Actual Combat Creation Engineering

In order not to affect the previous version, we create a new module spring-security-02 here. The previous version is spring-security-01. https://github.com/nimo10050/spring-security-sample/tree/master/spring-security-02

introducing dependency

The dependencies are the same as in the previous version, as follows:

org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web New SpringSecurity Configuration Class

Since we need to customize something, it can only be done by extra configuration. So here we introduce the spring-security configuration class

Add @Component annotation

Add Spring-security annotation EnableWebSecurity tag This is the configuration class for security

Inheriting WebSecurityConfigurerAdapter overrides its configuration methods

The configure(HttpSecurity http) method is rewritten to define the landing page

overriding configure(AuthenticationManagerBuilder auth) is to define login logic

package com.example.demo.config; import com.example.demo.config.service.UserDetailServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; [@Component](https://my.oschina.net/u/3907912) @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { [@Override](https://my.oschina.net/u/1162528) protected void configure(HttpSecurity http) throws Exception { http.csrf().disable();//must be present, otherwise 403 forbidden http.formLogin() The requested URL/loginPage.html was not found on this server. .loginProcessingUrl("/form/login");//custom login action, name any // passwordParameter("password") Configure the name attribute value of the form password // usernameParameter("username") Configure the name attribute value of the form username //visit "/form/login", "/loginPage.html" release http.authorizeRequests().antMatchers("/form/login", "/loginPage.html").permitAll() .anyRequest().authenticated(); } /** * Configure user login processing classes * * [@param](https://my.oschina.net/u/2303379) auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { /* Store user information in memory It's not actually going to happen, so just know it. auth.inMemoryAuthentication() .withUser("zhangsan") .password(passwordEncoder().encode("123456")) .authorities("admin");*/ auth.userDetailsService(userDetailsService()); } /** * Custom login processing * * @return */ @Bean public UserDetailsService userDetailsService() { return new UserDetailServiceImpl(); } /** * encryption tool * Spring-security-starter for version 2.x must be added * * @return */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

UserDetailService interface

Login logic is implemented by rewriting the loadUserByUsername method of the UserDetailService interface, where we can read the database or other storage medium to verify whether our user exists. Finally, configure the class we implemented into the config method.

/** * Custom login processing logic */public class UserDetailServiceImpl implements UserDetailsService {/* @Autowiredprivate PasswordEncoder passwordEncoder;*//** * @param username Login page Enter username * @return * @throws UsernameNotFoundException */@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO queries the user table for user information according to username, and then verifies it. //After successful verification, return the User object provided by Spring-Security //The corresponding three construction parameters are: 1. User name 2. Password (encrypted by passwordEncoder) 3. Permission list return new User(username, "$2a$10$g1gzj4KvMNY1kMZT1xDx9ufLuaDvCFDpX.PdETx85zQwXI/Mn4ttC", AuthorityUtils.createAuthorityList("admin"));}public static void main(String[] args) { System.out.println(new BCryptPasswordEncoder().encode("123456"));// $2a$10$g1gzj4KvMNY1kMZT1xDx9ufLuaDvCFDPX.PdETx85zQwXI/Mn4ttC}} Other points to note

You need to add http.csrf().disable() to the configure(HttpSecurity http) method; don't ask why, just add it.

When we rewrite the config method, spring-security will not intercept the resources we want to access, so we need to reconfigure them.

http.authorizeRequests().antMatchers("/form/login","/loginPage.html").permitAll().anyRequest().authenticated();

When we define UserDetailService, the console does not print the default password when the application starts.

Advanced versions of security must be configured with cryptographic tools. Otherwise, you'll get the wrong report.

passwordEncoder is null

About Spring security 02 how to customize the user login page and login processing logic questions to share here, I hope the above content can be of some help to everyone, if you still have a lot of doubts not solved, you can pay attention to the industry information channel to learn more related knowledge.

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

Internet Technology

Wechat

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

12
Report