1春のセキュリティ
Spring Securityは、SpringAOPおよびサーブレットフィルターに基づくセキュリティフレームワークです。包括的なセキュリティソリューションを提供し、Web要求レベルとメソッド呼び出しレベルでIDの検証と承認を処理します。
その設計は、フレームワーク内のさまざまな依存関係に基づいており、次のセクションに分けることができます。
(1)Web / Httpセキュリティ:これは最も複雑な部分です。フレームワークの認証メカニズムは、フィルターと関連するサービスBeanを確立することによって実現されます。保護されたURLにアクセスすると、ユーザーはログインインターフェイスまたはエラープロンプトインターフェイスを紹介されます。
(2)ビジネスオブジェクトまたはメソッドのセキュリティ:メソッドのアクセス権を制御します。
(3)AuthenticationManager:フレームワークの他の部分からの認証要求を処理します。
(4)AccessDecisionManager:Webまたはメソッドのセキュリティのためのアクセス決定を提供します。デフォルトのものが登録されますが、通常のBean登録を使用してカスタムAccessDecisionManagerを使用することもできます。
(5)AuthenticationProvider:AuthenticationManagerはそれを介してユーザーを認証します。
(6)UserDetailsService:AuthenticationProviderと密接に関連しており、ユーザー情報を取得するために使用されます。
2Maven依存関係を追加します
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3 SecurityConfig
リクエストの傍受を実行します。
package com.config;
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
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// 过滤请求
.authorizeRequests()
//允许匿名访问
.antMatchers("/test/help").anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
}
}
4リクエストURLを作成します
TestController.java:
package com.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/help")
public String help(){
return "hello,Help!";
}
@GetMapping("/login")
public String login(){
return "hello,login!";
}
}
5デバッグ結果
リクエストできるURLは結果を直接表示します。
リクエストできないURLの場合、403が表示されます。これは、アクセスする権限がないことを意味します。