Springでやりがちな事:Spring Securityのログイン画面が表示される

プロジェクト作成直後、最初の画面を作成する時に(多分)やらかしがちなこと。
Spring Security使用時、設定クラスに設定を記述しないとSpring Securityで用意されているログイン画面が表示される。

環境

  • Java: 11
  • Spring Boot: 2.3.3
  • Spring Security: 5.3.4

前提

Spring スターター・プロジェクトからプロジェクトを新規作成します。
プロジェクトで使用するライブラリは以下を選択します。

  • Spring Boot DevTools
  • Spring Security
  • Thymeleaf
  • Spring Web

以下のコードをプロジェクトに追加します。

hello.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
	<h1>Hello World</h1>

</body>
</html>

HelloController.java

package xyz.tenohira.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

	@GetMapping("/hello")
	public String getHello() {
		return "hello";
	}
}

実行し、http://localhost:8080/hello にアクセスすると、以下のようなSpring Securityのログイン画面が表示されます。

解決方法

Spring Securityを使用すると、何も設定しない状態では、全ての画面に対しアクセスするためには認証が必要となります。
ログインなしでアクセスできるようにするためには以下のようにします。

セキュリティ設定クラスとして、WebSecurityConfigurerAdapterクラスを継承しEnableWebSecurityアノテーションを付加したクラスを作成します。
void configure(HttpSecurity http)メソッドをオーバーライドし、以下のよう認証不要な画面(URL)を指定します。

SecurityConfig.java

package xyz.tenohira.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		// ログイン不要画面の設定
		http
			.authorizeRequests()
				.antMatchers("/hello").permitAll()
				.anyRequest().authenticated();
	}
}

上記の設定を行うことで、作成した画面が表示されるようになりました。