1、新建一個springboot項目,選擇web、thymeleaf、spring security
2、創建好當前文件和目錄結構
3、首先是一些相關的界面
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.ging</groupId> <artifactId>springboot-security</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-security</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</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> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-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>
welcome.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h1 align="center">歡迎光臨武林秘籍管理系統</h1> <div sec:authorize="!isAuthenticated()"> <h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">請登錄</a></h2> </div> <div sec:authorize="isAuthenticated()"> <h2 align="center"> <span sec:authentication="name"></span>,您好,您的角色有: <span sec:authentication="principal.authorities"></span> <form th:action="@{/logout}" method="post"> <input type="submit" value="注銷"/> </form> <h2> </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>
說明:重要的地方已經加粗放大了。
login.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1 align="center">歡迎登陸武林秘籍管理系統</h1> <hr> <div align="center"> <form th:action="@{/userlogin}" method="post"> 用戶名:<input name="username"/><br> 密碼:<input name="password"><br/> <input type="checkbox" name="remember">記住我<br/> <input type="submit" value="登陸"> </form> </div> </body> </html>
這里只展示其中一個1.html,它們大致相同:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a th:href="@{/}">返回</a> <h1>羅漢拳</h1> <p>羅漢拳站當央,打起來不要慌</p> </body> </html>
KungfuController.java
package com.ging.springbootsecurity.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; } }
MySecurityConfig.java
package com.ging.springbootsecurity.config; import org.springframework.context.annotation.Configuration; 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; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @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、設置轉到我們自己的登錄界面 //4、自定義的登錄界面要發送post請求,action需要為/login,字段要匹配這里的 http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login") //開啟自動配置的注銷功能 //1、訪問logout表示用戶注銷,清空session //2、默認注銷成功會返回login?logout頁面 //3、設置注銷成功來到首頁 http.logout().logoutSuccessUrl("/"); //開啟記住我功能 http.rememberMe().rememberMeParameter("remember"); } //定義認證規則 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")) .roles("VIP1","VIP2") .and() .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")) .roles("VIP2","VIP3"); } }
接下來跟着實際的操作一步步探索。
啟動服務器:
首先輸入localhost:8080,會自動跳轉到welcome.html,由於我們配置了authorizeRequests()和formLogin(),並且設置了/level?/**的權限,所以我們在瀏覽器輸入localhost:8080/level/1等請求時,由於沒有登錄,即不是哪一個用戶,所以會跳轉到springboot自定義的login界面。
如果我們不定義自己的登錄頁面的話,系統確實會跳轉到springboot自己的界面,但是我們若想要跳轉到自己的界面呢?
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/userlogin");//.loginProcessingUrl("/login")
這里需要設置用戶名和密碼的名稱,以及自動跳轉的頁面,即發送/userlogin請求,而/userlogin請求則會返回我們真正的登錄界面:login.html。在login.html中輸入框里面的name要和這里的分別對應,同時我們還要發送post請求,對應的action要與發送的請求相同,即為@{/userlogin}。我們設置記住我時,同樣要置http.rememberMe().rememberMeParameter("remember");對應的名稱。然后我們輸入:
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")) .roles("VIP1","VIP2") .and() .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")) .roles("VIP2","VIP3"); }
這里定義好的角色,一般這里是從數據庫中獲取,這里就只進行模擬。比如輸入:zhangsan,密碼:123456,我們就會進入到:
在welcome.html界面可以通過sec屬性來獲取相關的值。通過isAuthenticated來判斷當前的用戶是否具有權限,有的化我們的歡迎界面就變化了,顯名稱以及角色。然后在不同的代碼塊中我們有<div sec:authorize="hasRole('VIP1')">標識。zhangsan擁有“VIP1”和“VIP2”角色,因此可以看到普通武功秘籍和高級武功秘籍。我們點擊注銷,就可以退出登錄。在配置文件中定義了注銷后返回到主界面。由於此時沒有了權限,則會顯示歡迎您,游客。。。
接下來我們再試一下登錄:lisi 123456,並勾選記住我。
點進去看一本:
它是VIP2和VIP3,因此可以看到高級武功秘籍和絕世武功秘籍。由於我們勾選了記住我,所以我們關閉這個界面,在訪問localhost:8080,此時就不需要我們再進行登陸了。
總結:基本上實現了普通游客只有在登錄了之后才能夠訪問到level?/**下的內容,強行訪問會被攔截到登錄界面。用戶登陸之后根據不同角色顯示不同內容。勾選記住我后會保存一個cookie,再次訪問不需要再登錄,點擊注銷之后刪除cookie,退出登錄。