序文
主にShangシリコンバレーのSpringBoot統合バージョンのビデオに基づいて学習します
このプロジェクトのSpringBootのバージョンは2.4.1です。
SpringSecurityのバージョンは5.4.2です。
コントローラ層のコードは次のとおりです。
@Controller
public class KungfuController {
private final String PREFIX = "pages/";
/**
* 欢迎页
* @return
*/
@GetMapping("/")
public String index() {
return "welcome";
}
/**
* 登陆页
* @return
*/
@GetMapping("/userlogin")
public String loginPage() {
return PREFIX+"login";
}
/**
* level1页面映射
* @param path
* @return
*/
@GetMapping("/level1/{path}")
public String level1(@PathVariable("path")String path) {
return PREFIX+"level1/"+path;
}
/**
* level2页面映射
* @param path
* @return
*/
@GetMapping("/level2/{path}")
public String level2(@PathVariable("path")String path) {
return PREFIX+"level2/"+path;
}
/**
* level3页面映射
* @param path
* @return
*/
@GetMapping("/level3/{path}")
public String level3(@PathVariable("path")String path) {
return PREFIX+"level3/"+path;
}
}
これに基づいて、リソースファイルのパスを大まかに導き出すことができます
1. Spring Securityとは何ですか?
セキュリティフレームワーク:軽量のshiro、比較的重いSpringSecurity
公式の元の言葉を紹介します。SpringSecurityは、一般的な攻撃を防ぐための認証、承認、保護を提供するフレームワークです。命令型およびリアクティブ型アプリケーションのファーストクラスのサポートにより、Springベースのアプリケーションを保護するための事実上の標準です。
セキュリティフレームワークの基本機能:認証と承認(アクセス制御)
次に、手順を使用します
1.ライブラリを紹介します。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.WebSecurityConfigurerAdapterを継承する構成クラスを記述します
@EnableWebSecurityアノテーションは@Configuration構成クラスを宣言しているため、サブクラスはこのクラスを構成クラスとして宣言する必要はありません。
protected void configure(HttpSecurity http)メソッドを書き直して、リクエストの承認ルールをカスタマイズします。つまり、クライアントがリクエストを送信した後に、承認リクエストのauthorizeRequests()を定義します。
antMatchers( "/")は、すべてのリクエストを表すマッチングルールを設定します
.antMatchers( "/ level1 / **")。これは/ level1 /の下のすべてのリクエストを表します。
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
// 定制请求的授权规则:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
// 开启自动配置登录功能
// 1./login来到登录页
// 2.重定向到/login?error表示登录失败
// 3.更多详细规定
http.formLogin();
// 开启自动配置的注销功能
// 1.访问/logout 表示用户注销,清空session
// 2.注销成功会返回 /login?logout 页面
http.logout().logoutSuccessUrl("/");
}
// 定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
}
}
3.効果:
ログインしていない場合は、操作をクリックして、Spring自体が提供するログインページにジャンプします。