LoginSignup
3
3

More than 1 year has passed since last update.

Spring Security その1〜ログイン機能の実装

Posted at

はじめに

Spring Security を使用して、ログイン機能の実装です。

今回はデフォルトのログイン画面で、ユーザ認証もDBからは取得しません。
次回以降にDBから認証に必要な情報取得やカスタムログインページの作成をやる予定

バージョン

・Spring Boot3
・SpringSecurity6

プロジェクトの作成

image.png

image.png

image.png

image.png

image.png

application.properties の設定

(今回はDB接続は行いませんが、DBを使用する前提でプロジェクトは作成しているため、DBの設定が必要となる)

spring.jpa.database=POSTGRESQL
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=ユーザ名
spring.datasource.password=パスワード
logging.level.org.springframework=WARN
logging.level.jp.co.confrage.mapper.CustomerMapper=DEBUG

SecurityConfig.javaを作成する

現時点では何もカスタムなしです

package com.example.conf;

import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
        .formLogin()
        .and()
        .logout()
        .and()
        .authorizeHttpRequests(authz -> authz
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations())
                .permitAll()
                .anyRequest().authenticated()
        );
        return http.build();
    }
}

コントローラの作成

package com.example.controller;

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

@Controller
@RequestMapping("/")
public class DemoController {

	@GetMapping("toppage")
	public String toppage() {
		return "toppage";
	}

}

toppage(HTML)の作成

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>TOPPAGE</h1>
</body>
</html>

起動して、toppageにアクセス

  • 起動するとコンソールにログインパスワードが表示されます。
    image.png

  • http://localhost:8080/toppage にアクセスするとデフォルトのログイン画面が表示
    image.png

  • ユーザ名は「User」、パスワードはコンソールに出力されたパスワードを入力で認証が完了して、toppageが表示できました。
    image.png

今回はここまで、次はテーブルから認証に必要な情報を取得しよう

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