第一次使用Spring Boot集成 SpringBoot Security和JWT出现问题,找了很久没有到,官方SpringBoot Security5.0中新增了多种加密方式,也改变了默认的密码格式.,所以会出现这个问题。网上的问题大同小异,代码也都是差不多的,看花眼还是没对。

首先是在SecurityConfig配置类里面修改configure方法

  1. ** 错误代码
   @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("123")
                .roles("ADMIN");
    }
  1. ** 正确代码
@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123"))
                .roles("ADMIN");
                // 如果是连接数据库查询的话使用这行代码,将userDetailsService改为自己的就可以了。auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
  1. 在设置密码的时候使用BCryptPasswordEncoder()加密就行了!
    UserDetailsService里面也是一样的:
@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        // 调用方法查询用户
        User user = userDao.selectByName(username);

        if (user == null) {
            throw new RuntimeException("用户不存在");
        }


        // 存放权限
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        Map map = new HashMap();
        map.put("username",username);
        List<Role> roles = roleDao.selectRole(map);
        // 查询权限
        for (Role role:roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
        }
        // 重点看这个哦new BCryptPasswordEncoder().encode(user.getPassword())
        return new org.springframework.security.core.userdetails
                .User(username,new BCryptPasswordEncoder().encode(user.getPassword()),authorities);
    }

看完以后,如果对你有帮助给点❥(^_-)吧!!哈哈哈哈哈

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐