0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring securityのエラーメッセージをカスタムし、mesage.propertiesで一元管理する

Last updated at Posted at 2025-03-19

DaoAuthenticationProviderでカスタマイズしたらできる

前提

・messsage.propertiesの存在
・この三つの宣言

WebSecurityConfig
    private final UserDetailsService userDetailsService;
    private final MessageSource message;
    private final PasswordEncoder passwordEncoder;

ソース

message.properties
    @Bean
    AuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        provider.setMessageSource(message);
        return provider;
    }

解説

DaoAuthenticationProvider provider = new DaoAuthenticationProvider();

DaoAuthenticationProviderはユーザー名とパスワードを認証するやつ
newしてインスタンス化しとく

        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        provider.setMessageSource(message);

userDetailsServiceはデータベースからユーザー情報を取得するクラス
これをセットすることで、データベースと連携してログイン処理を行える。

        provider.setPasswordEncoder(passwordEncoder);

パスワードエンコーダーを自前でやったからセットしてる

        provider.setMessageSource(message);

ここが今回のミソ

    private final MessageSource message;

を宣言済みだからmessage.propertiesで管理することができる

キーの取得

使っているOS,IDEによって違ってしまうが、inteliJでは
ctrl + B
で宣言部に飛ぶことができる

ブレークポイントをメッセージを取得するところにセットし、そこから探せばキーが見つかるので横取りしてMessage.propertiesに記入しよう

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?