springboot集成springsecurity(自定义UserDetailsService)

时间:2024-10-23 18:31:58

依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<!--.... other-->
<dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
</dependency>

配置springSecurity

 @Bean
    PasswordEncoder encoder(){
        return  new BCryptPasswordEncoder();
    }

自定义UserDetailsService

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!"zhangsan".equals(username)){
            return null;
        }
        return User.builder()
                .username(username)
                .password("$2a$10$Dqn398CCfmv47tvaR3kMvOJ/1UQ9dTDZC4baqg0AqClqyiwJBeDVq")
                .roles("USER")
                .build();
    }
}
// 密码通过BCrypt加密获取
// System.out.println("密码:"+new BCryptPasswordEncoder().encode("123456"));

验证

  • 登录 127.0.0.0:8080/login
  • 输入用户名密码