Spring Boot/認証/Spring Security/HelloWorld/010_準備

単なるページの作成

とりあえずまずコントローラーを作って単にページを表示するだけのモノを1つ作る。

@Controller
@RequestMapping("/hoge")
public class HogeController {
    @RequestMapping("")
    public String index() {
        return "hoge/index";
    }
}

Thymeleaf を使ってるのでそのままテンプレを書く。 HTML 自体が間違っているが出ればいい。

<h1>hoge</h1>

http://localhost:8080/hoge

出た

Spring Security 用設定ファイルの作成

Spring Security 自体は Gradle か Maven で入れてある前提。

このような設定ファイルを書く。Javaのクラスとして書く。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
}

中身はまったく無し。これだけで Spring Security の効果が発現する。

さっきのここにアクセスすると hoge が表示されず

http://localhost:8080/hoge

ここにリダイレクトされる。

http://localhost:8080/login

そして作った覚えのない入力フォームが表示されている。

除外設定

全部をガードすると不便なので一部のページを除外する設定を書く。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/hoge");
    }
}

これで再び hoge ページを表示することができた。

オリジナルのログインページを作る

実用としてデフォルトのログインページは使い物にならないので、オリジナルのログインページを実装する。

まずはコントローラーを実装する。

@Controller
@RequestMapping("/mylogin")
public class LoginController {
    @RequestMapping("")
    public String index() {
        return "login/index";
    }
}

区別できるように mylogin とする。

テンプレを作る何も無し

<h1>Login</h1>

ログインするページなので当然除外なので除外する。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/hoge", "/mylogin");
    }
}

ここにアクセスしたら表示された。OK。

http://localhost:8080/mylogin

次はこのページをログインのページとして認識させる。 この場合は先ほとと違うメソッドで実装する。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/mylogin", "/hoge").permitAll()
                .anyRequest().authenticated();
    }
}

同じような除外設定が書けるので、ここに移植する。

次に mylogin をログインページとして認識させる。このようにする。

@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://localhost:8080/piyo

のような関係無いURLでアクセスすると mylogin に飛ばされるようになる。

この状態で試しに mylogin の除外設定を外してみると、リダイレクトがループする。 ログインページに指定しても除外設定は必要なようである。