0
点赞
收藏
分享

微信扫一扫

SpringBoot+SpringSecurity:自定义登录逻辑(模拟版本)

第一步:创建SpringSecurity配置文件

@Configuration
public class SpringSecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

第二步:自定义UserDetailsService

@Service
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中读取到的用户名
        if (!"zhangsan".equals(username)) {
            throw new UsernameNotFoundException("指定名称的用户不存在");
        }
        String password = passwordEncoder.encode("1234");

        User user = new User(username, password, AuthorityUtils.createAuthorityList());
        return user;
    }
}

第三步:启动项目测试

举报

相关推荐

0 条评论