スポンサーリンク

【SpringBoot】SpringSecurityの使い方。

Java
スポンサーリンク

 今回の記事では、SpringBootプロジェクトで簡単に認証機能を実装できるSpringSecurityの使い方をご紹介しています。SpringBootプロジェクトに認証機能を取り入れたいと考えている方や、SpringSecurityの使い方をもっと知りたい方は、是非参考にしてみてください。

スポンサーリンク

SpringSecurityの依存関係追加

gladleの場合は下記を追加。

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-security'
  testImplementation 'org.springframework.security:spring-security-test'
}

mavenの場合はpomファイルに下記を追加。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-security</artifactId>
</dependency>

これでSpringSecurityの準備はできたのでプロジェクトを作成していきます。

Spring Security実装

今回作成するアプリケーションの階層です。

.
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── demo
│   │   │               ├── DemoApplication.java
│   │   │               ├── MvcConfig.java
│   │   │               ├── ServletInitializer.java
│   │   │               └── WebSecurityConfig.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   │           ├── hello.html
│   │           └── login.html

MvcConfig

package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

	public void addViewControllers(ViewControllerRegistry registry) {
        // ルーティングの設定 
		registry.addViewController("/hello").setViewName("hello");
		registry.addViewController("/login").setViewName("login");
	}
}

上記でURLのルーティング設定をします。

WebSecurityConfig

package com.example.demo;

import org.springframework.context.annotation.Bean;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests((requests) -> requests
				.requestMatchers("/", "/home").permitAll()
				.anyRequest().authenticated()
			)
			.formLogin((form) -> form
				.loginPage("/login")
                .defaultSuccessUrl("/hello")
				.permitAll()
			)
			.logout((logout) -> logout.permitAll());

		return http.build();
	}

	@Bean
	public UserDetailsService userDetailsService() {
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER")
				.build();

		return new InMemoryUserDetailsManager(user);
	}
}

少し解説します。

    @Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests((requests) -> requests
				.requestMatchers("/", "/home").permitAll()
				.anyRequest().authenticated()
			)
			.formLogin((form) -> form
				.loginPage("/login")
                .defaultSuccessUrl("/hello")
				.permitAll()
			)
			.logout((logout) -> logout.permitAll());

		return http.build();
	}

上記の「formLogin」部分が認証処理のメイン部分です。

ログインページを開いた際に認証が成功した場合、defaultSuccessUrlで指定している認証成功後画面に遷移します。

認証処理は下記です。

	@Bean
	public UserDetailsService userDetailsService() {
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER")
				.build();

		return new InMemoryUserDetailsManager(user);
	}

今回の認証はユーザ名がuser、パスワードがpasswordでフォームに入力された値と一致すれば認証が通るようになっています。

テンプレート

ログイン画面

HTML「login.html」ファイルを下記のように記載。こちらはログイン画面になります。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

解説していきます。

<div th:if="${param.error}">
    Invalid username and password.
</div>

上記がエラーがあった場合の画面表示の切り替えです。

<div th:if="${param.logout}">
    You have been logged out.
</div>

上記は同様にログアウト時の切り替えです。

<form th:action="@{/login}" method="post">
    <div><label> User Name : <input type="text" name="username"/> </label></div>
    <div><label> Password: <input type="password" name="password"/> </label></div>
    <div><input type="submit" value="Sign In"/></div>
</form>

上記がログインフォームです。

inputタグのname属性「username」「password」を付与している項目が認証処理にPost通信される部分です。

ログイン成功後の画面

HTML「hello.html」ファイルを下記のように記載。こちらはログイン後の画面になります。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
    <head>
        <title>ログイン成功</title>
    </head>
    <body>
        <h1>ログイン成功
</h1>
    </body>
</html>

これで準備完了です。

アプリの起動

アプリ起動後「http://localhost:8080/login」をブラウザで開きます。

認証に失敗した場合

認証に成功した場合

以上で今回の記事は終了です。今回は認証処理を簡略化していますが、次回はDBの値を参照するなどを試してみます。

本記事を読んでいただき感謝です。サイトを訪れていただいた方はプログラミング勉強中かと思いますのでプログラミング勉強のコツを合わせてご紹介。

スポンサーリンク
スポンサーリンク
スポンサーリンク

ブログに関しては500円程度かかりますが、それ以外は無料です。知識の吸収と並行してアウトプットは非常に効率が良いです。テックアカデミーに関しては講座レベルが高いにも関わらず、無料体験や人気口座も大幅値下げがあるので、重点的に学びたいものを無料体験してみてください。

転職時にも、エンジニアからテックアカデミー・Paizaは認知度が高いので、未経験入社採用を行う際履歴書で目に留まります。特にPaizaのスキルレベルA・SなどはIT業界でも評価されます。

テックアカデミー・Paizaの無料登録ができる期間中にぜひご利用してみてください。私も活用経験ありです。

Java
スポンサーリンク
スポンサーリンク

コメント

タイトルとURLをコピーしました