LoginSignup
6

More than 5 years have passed since last update.

SpringSecutiryで例外メッセージを変更するのーと

Posted at
  • Spring Boot 1.4.3.RELEASE
  • Spring Security 4.1.4.RELEASE (4.2.1.RELEASEでも同様)

Spring SecurityでUserDetailsServiceを実装し、認証失敗時のメッセージを変更したい。

対象外

以下のいずれかに該当する場合は対象外です。

  • Spring Securityのメッセージを使用しない
  • Spring Security 4.1.0.RELEASEの機能を使わない
  • AuthenticationProviderを実装している
  • UserDetailsServiceを使わない

想定手順と説明

  1. UserDetailsServiceを実装してBean定義する。
  2. messages.propertiesにSpring Securityのキーでメッセージを追加する。

以上。

UserDetailsServiceの実装 (してない)

@Service
public class MyUserDetailsService implements UserDetailsService {
   // いい感じに実装する
}

messages.properties (抜粋)

AbstractUserDetailsAuthenticationProvider.badCredentials=ユーザーIDかパスワードが違います。

キーはデフォルトのmessages.properties を参照するのが早い。ドキュメントは見つけられていない。

説明

4.1.0で追加された InitializeUserDetailsBeanManagerConfigurer が、AuthenticationManagerBuilderが未設定の場合のみ動作。
コンテナからUserDetailsServicePasswordEncoderを拾ってきてDaoAuthenticationProviderを作って登録してくれる。
AuthenticationManagerBuilderの設定は不要。

・・・であるはずだった。

期待はずれの挙動

例外メッセージがデフォルトから変わらず、「Bad credentials」になる。
MessageResourceがあればMessageSourceAwareで書き換えられる想定だった。

MessageResourceはSpring Bootが作ってくれている。
にもかかわらず、DaoAuthenticationProviderMessageSourceAccessorSpringSecurityMessageSourceのままである。

この場の解決

AuthenticationManagerBuilderを使って設定しておけばDaoAuthenticationConfigurerを介して設定してくれる。

つまり、いままで通りに以下を記述する。

@Autowired
void authenticationManagerBuilder(AuthenticationManagerBuilder builder,
    UserDetailsService service) {
    builder.userDetailsService(service).passwordEncoder(passwordEncoder());
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6