Spring Security 4.x -> 5.x 踩坑記錄

1、應用服務基路徑問題

這個問題應該是Spring Boot 2.0升級帶來的,既然遇到了,就在這裏寫一寫。筆者在授權服務器想設置一個統一基路徑,按照Spring Boot 1.0,是這樣的:

server.context-path=/xxx

但是升級之後並不好使,最後看官方文檔發現改掉了,現在是這樣的:

server.servlet.context-path=/xxx

2、AuthenticationManager無法注入

在覆寫AuthorizationServerConfigurerAdapter類的public void configure(AuthorizationServerEndpointsConfigurer endpoints) 方法時,往往需要顯式注入AuthenticationManager ,但是在5.x版本中,啓動會報如下錯誤:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field authenticationManager in cn.springcloud.book.OAuthConfiguration required a bean of type 'org.springframework.security.authentication.AuthenticationManager' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.security.authentication.AuthenticationManager' in your configuration.

解決方案:
在啓動主類繼承WebSecurityConfigurerAdapter 類同時,手動注入:

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

3、登陸報錯:There is no PasswordEncoder mapped for the id “null”

在使用Spring Security 5.x登陸頁面進行登陸時,後端會報錯:There is no PasswordEncoder mapped for the id “null”,因爲5.x版本新增了多種密碼加密方式,必須指定一種,比如這樣解決:

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
      return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

下列加密方式供參考,選取一種即可:

bcrypt - BCryptPasswordEncoder (Also used for encoding)
ldap - LdapShaPasswordEncoder
MD4 - Md4PasswordEncoder
MD5 - new MessageDigestPasswordEncoder("MD5")
noop - NoOpPasswordEncoder
pbkdf2 - Pbkdf2PasswordEncoder
scrypt - SCryptPasswordEncoder
SHA-1 - new MessageDigestPasswordEncoder("SHA-1")
SHA-256 - new MessageDigestPasswordEncoder("SHA-256")
sha256 - StandardPasswordEncoder
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章