0
2

More than 1 year has passed since last update.

(新)【SpringBoot】Spring Security を用いてDBにアクセスして認証を行う

Last updated at Posted at 2022-08-18

Spring Securityの設定方法についての備忘です。

前回、5.7以前の書き方で記事を書きましたが、5.7以降の書き方に変更したので、変更箇所を執筆します。
前回の記事はこちら

Configクラスの修正

✓ ポイント

  • WebSecurityConfigurerAdapter を継承せずに SecurityFilterChain をBean定義して設定の記述を行う
SecurityConfig.java
package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.example.authentication.CustomUserDetailsService;

@EnableWebSecurity
public class SecurityConfig {  // WebSecurityConfigurerAdapterは継承しない

    // SecurityFilterChainをBean定義する
    @Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		
        // config(HttpSecurity http)のオーバーライドしたメソッド内でやっていたことと同じ

        // 以下ログインに関する設定。書き方は以前と同様
		http.formLogin(login -> login
				.loginProcessingUrl("/login").permitAll() //ログインのURL
				.loginPage("/login").permitAll()
				.usernameParameter("name")
				.passwordParameter("password")
				.failureUrl("/login?failed")
				.defaultSuccessUrl("/item/list")
				
            // 以下ログアウトに関する設定。書き方は以前と同様
			).logout(logout -> logout 
				.logoutUrl("/logout").permitAll()
				.logoutSuccessUrl("/login")
				.invalidateHttpSession(true)
				.deleteCookies("JSESSIONID")
			
            // URLごとの認可設定を下記で行う。書き方は以前と同様
			).authorizeHttpRequests(authz -> authz
	            .mvcMatchers("/login/**", "/user/**", "/rest/**", "/img/**", "/css/**", "/js/**").permitAll()
	            .anyRequest().authenticated()
	        );
			
		
        // Bean登録
		return http.build();
	}
	
    // PasswordEncoderもBean登録する。これが無いと、PasswordEncoderがありませんというエラーがでる。
	@Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
	
}

終わりに

SpringSecurityについて検索すると、WebSecurityConfigurerAdapter を継承した以前の書き方ばかり出てくるので、この記事が誰かの一助になれば幸いです。間違っている部分もあるかと思いますので、その際はご指摘頂ければと思います。

参考文献

Spring Security 5.7でセキュリティ設定の書き方が大幅に変わる件
Configure HTTP Security without extending WebSecurityConfigurerAdapter
最新の5.7で学ぶ!初めてのひとのためのSpring Security

0
2
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
0
2