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"。

  源碼很重要啊!!!以后有時間多看一點。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM