Spring Security-user authentication

Two important interfaces

  1. UserDetailsService interface
    1. Query database user name and password
    2. Create a class to inherit UsernamePasswordAuthenticationFilter and rewrite three methods
    3. Create a class to implement UserDetailsService, write a database query process, and return the User object, which is an object provided by the security framework
  2. PasswordEncode interface
    1. Data encryption interface, used to return the password encryption in the User object

Set login username and password

  1. Via configuration file
spring.security.user.name=fy
spring.security.user.password=fy123
  1. Through the configuration class
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123");
        auth.inMemoryAuthentication().withUser("fyun").password(password).roles("admin");
    }
    @Bean
    PasswordEncoder passwordEncoder(){
    
    
        return new BCryptPasswordEncoder();
    }
}
  1. Custom write implementation class
    1. Create a configuration class and set which UserDetailsService implementation class to use
    @Configuration
     public class MySecurityConfig extends WebSecurityConfigurerAdapter {
          
          
    
         @Autowired
         private UserDetailsService userDetailsService;
         @Override
         protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          
          
             auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
         }
         @Bean
         PasswordEncoder passwordEncoder(){
          
          
             return new BCryptPasswordEncoder();
         }
     }
    
    1. Write the implementation class, return the User object, the User object has the user name, password and operation authority
    @Service("userDetailsService")
    public class MyUserDetailsService implements UserDetailsService {
          
          
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
          
          
            List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
            return new User("may",new BCryptPasswordEncoder().encode("my123"),role);
        }
    }
    

Query the database to complete user authentication

Integrate MybatisPlus to complete database operations

  1. Introduce related dependencies
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. Create database and data table
CREATE TABLE USER(
id INTEGER AUTO_INCREMENT,
username VARCHAR(225) ,
PASSWORD VARCHAR(225),
PRIMARY KEY (id)
);
  1. Create User entity class
@Data
public class User {
    
    
    private Integer id;
    private String username;
    private String password;
}
  1. Integrate MybatisPlus
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  1. Write UserMapper interface
@Repository
public interface UserMapper extends BaseMapper<User> {
    
    
}
  1. write
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    
    

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
    
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        User user = userMapper.selectOne(wrapper);
        if (user == null){
    
    
            throw new UsernameNotFoundException("用户名不存在!");
        }
        List<GrantedAuthority> role = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new org.springframework.security.core.userdetails.User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),role);
    }
}
  1. Configure data source
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.138.236.45/security?serverTimezone=GMT%2B8

Custom login page

  1. Override the configure method in the configuration class
@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
    http.formLogin()    //自定义自己编写的登录页面
            .loginPage("/login.html")   //登录页面设置
            .loginProcessingUrl("/user/login")  //登录访问路径
            .defaultSuccessUrl("/test/index").permitAll()   //登录成功之后的跳转路径
            .and().authorizeRequests()
            .antMatchers("/","/test/hello","/user/login").permitAll()   //设置哪些路径可以直接访问
            .anyRequest().authenticated()
            .and().csrf().disable();    //关闭csrf防护
}
  1. Edit the login page
    . The name attribute of the username and password must be "username" and "password"
<form action="/user/login" method="post">
    用户名:<input type="text" name="username">
    <br>
    密码:<input type="text" name="password">
    <br>
    <input type="submit" value="login">
</form>

Guess you like

Origin blog.csdn.net/qq_40857365/article/details/112857254