LoginSignup
1
1

More than 5 years have passed since last update.

Spring Securityのフォーム認証エラーでユーザーを保持

Posted at

Spring Securityのフォーム認証で認証できなかった場合、ユーザーとパスワードのフィールド両方がクリアされます。セキュリティ的にはその方がよいのかもしれませんが、やっぱり不便なのでユーザーは残すような方法を考えてみました。

ログイン失敗時にユーザーを何らかの形で保持しておけばよいので、今回は手っ取り早くクエリパラメータにusername=ユーザーで保持する様にします。ユーザーを保持できればよいので、リクエストスコープやセッションスコープを使っても実現できると思います。

formLoginの設定でfailureHandlerを設定し、URLを組み立ててリダイレクトするようにします。

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/css/**", "images/**").permitAll()
                .antMatchers("/**").authenticated()
                .and()
            .formLogin()
                .loginPage("/loginForm")
                .defaultSuccessUrl("/", true)
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .failureHandler((req, res, exp) -> {
                    res.sendRedirect("/loginForm?error=true&username=" + req.getParameter("username"));
                })
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/loginForm");
    }
}

ビューにThymeleafを使う場合は

<input type="text" placeholder="ユーザー" name="username"
  th:value="${param.username != null } ? ${param.username[0]} : ''"/>

こんな感じでクエリパラメータを設定すれば、ログイン失敗時にユーザーが保持されます。

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