SpringBoot Security:Encoded password does not look like BCrypt 解决

第一次使用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);
    }

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

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT界的渣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值