Spring Security搭建过程问题总结

  学习Spring Security框架过程中遇到的问题总结!  

  运行程序,注册用户,输入用户名、密码,报错:There is no PasswordEncoder mapped for the id “null”

  分析:Spring Security 5.0  以上的版本采用了bcrypt的加密方式,所以需要指定一个encodingId,如果不指定,就会报出上文所示的错误。

  解决方法需要在WebSecurityConfig自定义类中指定密码的加密方式,所以当注册用户往数据库插入用户信息时,也需要对密码进行BCrypt方式的加密,用户登录时密码才能进行有效的对应。

 @Override
     protected void configure(AuthenticationManagerBuilder builder) throws Exception{
         builder.userDetailsService(anyUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
     //如果你还是想采用明文密码,需要配置密码验证方式为noop,不过5.0版本不推荐这样使用
     
builder.userDetailsService(anyUserDetailsService).passwordEncoder(new NoOpPasswordEncoder ());
}

  

  配置HttpSecurity对象中URL的访问权限时,需要注意hasRole方法中参数的写法,直接看源码

private static String hasRole(String role) {
        Assert.notNull(role, "role cannot be null");
        if (role.startsWith("ROLE_")) {
            throw new IllegalArgumentException(
                    "role should not start with 'ROLE_' since it is automatically inserted. Got '"
                            + role + "'");
        }
        return "hasRole('ROLE_" + role + "')";

它是默认在权限比较时,在传入参数前加上"ROLE_",所以如果你传入的参数是"USER",那么访问URL所需的权限就是"ROLE_USER",也就是说你定义用户权限时需要指定为"ROLE_USER"。

  源码很重要啊!!!以后有时间多看一点。

  

猜你喜欢

转载自www.cnblogs.com/linyukun/p/9863559.html
今日推荐