menu
書いてる野郎
orebike@gmail.com
サイト全体をガードする。ログイン画面が出る。というところまで来たので、入力フォームを準備してみる。
Thymeleaf 的に書いてみる。
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form method="post" th:action="@{'/doLogin'}"> id: <input type="text" name="login_id" /> password: <input type="password" name="login_password" /> <input id="login_button" type="submit" value="login" /> </form> </body> </html>
そうするとこのような HTML が生成される。
<!DOCTYPE HTML> <html> <head> <title>Login</title> </head> <body> <h1>Login</h1> <form method="post" action="/doLogin"><input type="hidden" name="_csrf" value="e4e978a5-b299-40ef-b091-78904404b804"/> id: <input type="text" name="login_id" /> password: <input type="password" name="login_password" /> <input id="login_button" type="submit" value="login" /> </form> </body> </html>
CSRF 対策が勝手にやられるようになっている。 今回は簡単にしたいのでこいつは抑制したい。 このように1行書くと抑制される。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/mylogin", "/hoge").permitAll() .anyRequest().authenticated(); http .formLogin() .loginPage("/mylogin"); http.csrf().disable(); } }
HTML 側で勝手に書いたがパラメータが /doLogin
に送られると認証するということにした。
なので Spring Boot 側でもそれを認識させたいので設定する。
各パラメータも対応させる。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/mylogin", "/hoge").permitAll() .anyRequest().authenticated(); http .formLogin() .loginPage("/mylogin") .loginProcessingUrl("/doLogin") .usernameParameter("login_id") .passwordParameter("login_password"); http.csrf().disable(); } }
これで form と Java の対応が済んだ。
ログイン後の画面として Top ページを作っておく。
@Controller @RequestMapping("/top") public class TopController { @RequestMapping("") public String index() { return "top/index"; } }
試しにアクセスしてみてログイン画面に飛ばされることを確認。
それではログイン後に top に遷移させるように設定。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/mylogin", "/hoge").permitAll() .anyRequest().authenticated(); http .formLogin() .loginPage("/mylogin") .loginProcessingUrl("/doLogin") .usernameParameter("login_id") .passwordParameter("login_password") .defaultSuccessUrl("/top"); // This!! http.csrf().disable(); } }
それではログインしてみる。
認証する機構はまったく実装していないが Spring Security ではそのへんもやってくれていて、
デフォルトでまずパスワードを自動生成してくれている。Spring Boot を起動するときにコンソールに出力されているはずである。そしてデフォルトのユーザー名は user
なのでこの2つを使ってログインできるか試す。
やるとうまくトップ画面に遷移したことがわかる。 設定は正しく動いているようだ。