質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Spring Security

Spring Securityは、Springのサブプロジェクトの一つでWebアプリケーションに必要な機能を追加します。正規ユーザーであるかを確認するための「認証機能」と、ユーザーのアクセスを制御する「認可機能」を簡単に追加することが可能です。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

Q&A

解決済

1回答

5318閲覧

SpringSecurity5.7におけるAuthenticationManagerBuilderをどのように代替するか

Riku-smile

総合スコア12

Spring Security

Spring Securityは、Springのサブプロジェクトの一つでWebアプリケーションに必要な機能を追加します。正規ユーザーであるかを確認するための「認証機能」と、ユーザーのアクセスを制御する「認可機能」を簡単に追加することが可能です。

Java

Javaは、1995年にサン・マイクロシステムズが開発したプログラミング言語です。表記法はC言語に似ていますが、既存のプログラミング言語の短所を踏まえていちから設計されており、最初からオブジェクト指向性を備えてデザインされています。セキュリティ面が強力であることや、ネットワーク環境での利用に向いていることが特徴です。Javaで作られたソフトウェアは基本的にいかなるプラットフォームでも作動します。

Spring

Spring Framework は、Javaプラットフォーム向けのオープンソースアプリケーションフレームワークです。 Java Platform上に、 Web ベースのアプリケーションを設計するための拡張機能が数多く用意されています。

Spring Boot

Spring Bootは、Javaのフレームワークの一つ。Springプロジェクトが提供する様々なフレームワークを統合した、アプリケーションを高速で開発するために設計されたフレームワークです。

0グッド

0クリップ

投稿2022/08/13 05:34

前提

本記事 -08ログイン・ログアウトの実装に従ってハンズオンでコードを書いています。

SpringSecurity5.7より、extendsされているWebSecurityConfigurerAdapterがdeprecatedされます。

本記事のパスワード照会部分では

java

1@EnableWebSecurity 2@RequiredArgsConstructor 3public class SecurityConfig extends WebSecurityConfigurerAdapter { 4 5 private final UserDetailsManager userDetailsManager; 6 private final PasswordEncoder passwordEncoder; 7 8 @Override 9 public void configure(HttpSecurity http) throws Exception { 10 http.authorizeRequests() 11 .antMatchers("/h2-console/**").hasRole("ADMIN") 12 .antMatchers("/board").hasRole("USER") 13 .and().formLogin() 14 .loginPage("/user").permitAll() // ログインページのカスタマイズ 15 .defaultSuccessUrl("/board") // ログイン認証ページの要求, ログイン成功後デフォルト画面の設定 16 .and().csrf().ignoringAntMatchers("/h2-console/**") 17 .and().headers().frameOptions().sameOrigin(); 18 } 19 20 @Override 21 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 22 auth.userDetailsService(userDetailsManager).passwordEncoder(passwordEncoder); 23 } 24 25 @Override 26 public void configure(WebSecurity web) throws Exception { 27 // Configure a new SecurityChainFilter 28 web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); 29 } 30 31}

と表記されているため、SpringSecurity5.7~の表記に変えて実装を行いたいです。

実現したいこと

  • AuthenticationManagerBuilderをSpringSecurity5.7~の記法で実装したいです。
  • ユーザーの登録したパスワードとリクエストされたパスワードの照会部分を実装したいです。

発生している問題・エラーメッセージ

実装方法に見当がつきません。

該当のソースコード

java

1// root/config/SecurityConfig.java 2@EnableWebSecurity 3public class SecurityConfig { 4 5 private final UserDetailsManager userDetailsManager; 6 private final PasswordEncoder passwordEncoder; 7 8 // configure(HttpSecurity http) 9 @Bean 10 public SecurityFilterChain securityFilterChain(HttpSecurity http) 11 throws Exception { 12 13 http.authorizeRequests().antMatchers("/h2-console/**").hasRole("ADMIN") 14 .antMatchers("/board").hasRole("USER") 15 .and().formLogin() 16 .loginPage("/user").permitAll() 17 .defaultSuccessUrl("/board") 18 .and().csrf().ignoringAntMatchers("/h2-console/**") 19 .and().headers().frameOptions().sameOrigin(); 20 return http.build(); 21 } 22 23 // configure(AuthenticationManagerBuilder auth) 24 25 // configure(WebSecurity web) 26 @Bean 27 public WebSecurityCustomizer webSecurityCustomizer() { 28 return (web) -> web.ignoring().requestMatchers( 29 PathRequest.toStaticResources().atCommonLocations()); 30 } 31}

java

1// root/infrastracture/datasource/Config/DatasourceConfig.java 2@Configuration 3@RequiredArgsConstructor 4public class DatasourceConfig { 5 6 private final DataSource dataSource; 7 8 @Bean 9 public UserDetailsManager userDetailsManager() { 10 return new JdbcUserDetailsManager(dataSource); 11 } 12 13 @Bean 14 public PasswordEncoder passwordEncoder() { 15 return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 16 } 17} 18

試したこと

補足情報(FW/ツールのバージョンなど)

xml

1<!-- pom.xml --> 2<?xml version="1.0" encoding="UTF-8"?> 3<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <parent> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-parent</artifactId> 9 <version>2.7.2</version> 10 <relativePath/> <!-- lookup parent from repository --> 11 </parent> 12 <groupId>com.example</groupId> 13 <artifactId>ashitaba-hands-on</artifactId> 14 <version>0.0.1</version> 15 <name>ashitaba-hands-on</name> 16 <description>[https://zenn.dev/angelica/books/52be1e365c61ea]の実践</description> 17 <properties> 18 <java.version>17</java.version> 19 </properties> 20 <dependencies> 21 <dependency> 22 <groupId>org.springframework.boot</groupId> 23 <artifactId>spring-boot-starter-thymeleaf</artifactId> 24 </dependency> 25 26 <!-- Tymleafのlayout --> 27 <dependency> 28 <groupId>nz.net.ultraq.thymeleaf</groupId> 29 <artifactId>thymeleaf-layout-dialect</artifactId> 30 </dependency> 31 <!-- validationしたいので --> 32 <dependency> 33 <groupId>org.springframework.boot</groupId> 34 <artifactId>spring-boot-starter-validation</artifactId> 35 </dependency> 36 37 <!-- DB --> 38 <dependency> 39 <groupId>org.mybatis.spring.boot</groupId> 40 <artifactId>mybatis-spring-boot-starter</artifactId> 41 <version>2.1.4</version> 42 </dependency> 43 <dependency> 44 <groupId>org.mybatis.scripting</groupId> 45 <artifactId>mybatis-thymeleaf</artifactId> 46 <version>1.0.2</version> 47 </dependency> 48 <dependency> 49 <groupId>com.h2database</groupId> 50 <artifactId>h2</artifactId> 51 <version>1.4.200</version> 52 <!--<scope>test</scope> 本来テストスコープだけで使うべき--> 53 </dependency> 54 55 <!-- セキュリティー --> 56 <dependency> 57 <groupId>org.springframework.boot</groupId> 58 <artifactId>spring-boot-starter-security</artifactId> 59 </dependency> 60 61 <dependency> 62 <groupId>org.springframework.boot</groupId> 63 <artifactId>spring-boot-starter-web</artifactId> 64 </dependency> 65 66 <dependency> 67 <groupId>org.springframework.boot</groupId> 68 <artifactId>spring-boot-devtools</artifactId> 69 <scope>runtime</scope> 70 <optional>true</optional> 71 </dependency> 72 <dependency> 73 <groupId>org.springframework.boot</groupId> 74 <artifactId>spring-boot-configuration-processor</artifactId> 75 <optional>true</optional> 76 </dependency> 77 <dependency> 78 <groupId>org.projectlombok</groupId> 79 <artifactId>lombok</artifactId> 80 <optional>true</optional> 81 </dependency> 82 <dependency> 83 <groupId>org.springframework.boot</groupId> 84 <artifactId>spring-boot-starter-test</artifactId> 85 <scope>test</scope> 86 </dependency> 87 </dependencies> 88 89 <build> 90 <plugins> 91 <plugin> 92 <groupId>org.springframework.boot</groupId> 93 <artifactId>spring-boot-maven-plugin</artifactId> 94 <configuration> 95 <excludes> 96 <exclude> 97 <groupId>org.projectlombok</groupId> 98 <artifactId>lombok</artifactId> 99 </exclude> 100 </excludes> 101 </configuration> 102 </plugin> 103 </plugins> 104 </build> 105 106</project> 107

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

結論から言うとclass構成を書き換えると

java

1public class SecurityConfig { 2 3 @Bean 4 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 5 http.authorizeRequests() 6 .antMatchers("/h2-console/**").hasRole("ADMIN") 7 .antMatchers("/board").hasRole("USER") 8 .and().formLogin() 9 .loginPage("/user").permitAll() // ログインページのカスタマイズ 10 .defaultSuccessUrl("/board") // ログイン認証ページの要求, ログイン成功後デフォルト画面の設定 11 .and().logout() 12 .logoutUrl("/user/logout") 13 .logoutSuccessUrl("/user") 14 .and().csrf().ignoringAntMatchers("/h2-console/**") 15 .and().headers().frameOptions().sameOrigin(); 16 return http.build(); 17 } 18 19 @Bean 20 public WebSecurityCustomizer webSecurityCustomizer() { 21 return web -> web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations()); 22 } 23 24}

のようになります。

修正いただいたとおり、HttpSecurityのカスタマイズはsecurityFilterChainで可能であり、WebSecurityはWebSecurityCustomizerで可能です。

AuthenticationManagerBuilderはissueの方でSpringSecurityの偉人が書いていますが、自動構成されるようになっており、UserDetailsManagerとPasswordEncoderをDIコンテナに登録しておけば勝手にそれらを使用して作成されるようになりました。
なのでAuthenticationManagerBuilderを書く必要はありません。

(AuthenticationManagerを自分でDIコンテナに入れると、重複でエラーが発生しアプリケーションがクラッシュします。
重複するということはもうできているということなので、試しに作らずに起動させると、bcrypt化しているパスワードを持つユーザにログインできました。つまり、入力パスワードをbcryptにしているのでAuthenticationManagerが構成されているのは自明です。ということで、本家に裏とりにいってみつけました。
特に自分はSpringSecurityに詳しくはないので、付け焼き刃の回答になります。)

ご覧頂いたzennの内容についても近々修正しようとは思っております。お手数おかけしました。

投稿2022/08/16 14:39

編集2022/08/16 14:48
ange.k

総合スコア13

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Riku-smile

2022/08/19 04:05

ご回答いただきありがとうございます。 自動構成されるようになっていたのですね。 公式ドキュメントを参照する癖まではついたのですが、ソースコードやissueまで情報を取りに行くことはしていませんでした。 今後行き詰った時は意識してみようと思います。 プルリクでの修正もありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問