引言:如下文檔是學習尚硅谷關於springboot教學視頻後整理而來! html
1、安全java
認證(Authentication):證實你是誰?web
受權(Authorization):你能幹什麼?spring
參考資料:apache
Spring Boot+Spring Security+Thymeleaf 簡單教程瀏覽器
Spring Security 參考手冊 (中文api)安全
Spring Security (英語api)springboot
Spring Security是針對Spring項目的安全框架,也是Spring Boot底層安全模塊默認的技術選型。他能夠實現強大的web安全控制。cookie
對於安全控制,咱們僅需引入spring-boot-starter-security模塊,進行少許的配置,便可實現強大的安全管理。幾個類:
WebSecurityConfigurerAdapter:自定義Security策略
AuthenticationManagerBuilder:自定義認證策略
@EnableWebSecurity:開啓WebSecurity模式
2、Web&安全
一、登錄/註銷
HttpSecurity配置登錄、註銷功能
二、Thymeleaf提供的SpringSecurity標籤支持
須要引入thymeleaf-extras-springsecurity4 (thymeleaf與springsecurity的整合模塊)
sec:authentication=「name」得到當前用戶的用戶名
sec:authorize=「hasRole(‘ADMIN’)」當前用戶必須擁有ADMIN權限時纔會顯示標籤內容
三、remember me
表單添加remember-me的checkbox
配置啓用remember-me功能
四、CSRF(Cross-site request forgery)跨站請求僞造
HttpSecurity啓用csrf功能,會爲表單添加_csrf的值,提交攜帶來預防CSRF;
使用步驟:
/** * 一、引入SpringSecurity; * 二、編寫SpringSecurity的配置類; * @EnableWebSecurity extends WebSecurityConfigurerAdapter * 三、控制請求的訪問權限: * configure(HttpSecurity http) { * http.authorizeRequests().antMatchers("/").permitAll() * .antMatchers("/level1/**").hasRole("VIP1") * } * 四、定義認證規則: * configure(AuthenticationManagerBuilder auth){ * auth.inMemoryAuthentication() * .withUser("zhangsan").password("123456").roles("VIP1","VIP2") * } * 五、開啓自動配置的登錄功能: * configure(HttpSecurity http){ * http.formLogin(); * } * 六、註銷:http.logout(); * 七、記住我:Remeberme(); */
一、pom.xml架包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.atguigu</groupId> <artifactId>springboot-05-security</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-05-security</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version> <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 --> <!--thymeleaf與springsecurity4的整合包--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!--SpringSecurity包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
二、編寫springsecurity配置類
package com.atguigu.security.config; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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 MySecurityConfig extends WebSecurityConfigurerAdapter { /** * 定義受權規則 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定製請求的受權規則 http.authorizeRequests().antMatchers("/").permitAll() //全部人都能訪問 .antMatchers("/level1/**").hasRole("VIP1") //只有角色爲VIP1的用戶才能訪問,才能訪問路徑/level1/**下的全部資源 .antMatchers("/level2/**").hasRole("VIP2") .antMatchers("/level3/**").hasRole("VIP3"); //開啓自動配置的登錄功能,效果,若是沒有登錄,沒有權限就會來到登錄頁面 //一、/login來到登錄頁 //二、重定向到/login?error表示登錄失敗 //三、更多詳細規定 //四、默認post形式的 /login表明處理登錄 //五、一但定製loginPage;那麼 loginPage的post請求就是登錄 http.formLogin().usernameParameter("user").passwordParameter("pwd") .loginPage("/userlogin"); //開啓自動配置的註銷功能。 //一、訪問 /logout 表示用戶註銷,清空session //二、註銷成功會返回 /login?logout 頁面; http.logout().logoutSuccessUrl("/");//註銷成功之後來到首頁 //開啓記住我功能 //登錄成功之後,將cookie發給瀏覽器保存,之後訪問頁面帶上這個cookie,只要經過檢查就能夠免登陸 //點擊註銷會刪除cookie http.rememberMe().rememberMeParameter("remeber"); } /** * 定義認證規則 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //super.configure(auth); auth.inMemoryAuthentication() //在內存裏面查用戶 .withUser("zhangsan").password("123456").roles("VIP1","VIP2") .and() .withUser("lisi").password("123456").roles("VIP2","VIP3") .and() .withUser("wangwu").password("123456").roles("VIP1","VIP3"); } }
controller層:(不是主要的)
package com.atguigu.security.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @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; } }
thymeleaf模板:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1 align="center">歡迎光臨武林祕籍管理系統</h1> <!--若是沒有被認證這顯示如下div--> <div sec:authorize="!isAuthenticated()"> <h2 align="center">遊客您好,若是想查看武林祕籍 <a th:href="@{/userlogin}">請登陸</a></h2> </div> <!--若是用戶已經被認證--> <div sec:authorize="isAuthenticated()"> <!--用戶的名字--> <h2><span sec:authentication="name"></span>,您好,您的角色有: <!--用戶所擁有的角色--> <span sec:authentication="principal.authorities"></span></h2> <form th:action="@{/logout}" method="post"> <input type="submit" value="註銷"/> </form> </div> <hr> <div sec:authorize="hasRole('VIP1')"> <h3>普通武功祕籍</h3> <ul> <li><a th:href="@{/level1/1}">羅漢拳</a></li> <li><a th:href="@{/level1/2}">武當長拳</a></li> <li><a th:href="@{/level1/3}">全真劍法</a></li> </ul> </div> <div sec:authorize="hasRole('VIP2')"> <h3>高級武功祕籍</h3> <ul> <li><a th:href="@{/level2/1}">太極拳</a></li> <li><a th:href="@{/level2/2}">七傷拳</a></li> <li><a th:href="@{/level2/3}">梯雲縱</a></li> </ul> </div> <div sec:authorize="hasRole('VIP3')"> <h3>絕世武功祕籍</h3> <ul> <li><a th:href="@{/level3/1}">葵花寶典</a></li> <li><a th:href="@{/level3/2}">龜派氣功</a></li> <li><a th:href="@{/level3/3}">獨孤九劍</a></li> </ul> </div> </body> </html>
頁面效果:
項目結構: