一、安全
Spring Security是針對Spring項目的安全框架,也是Spring Boot底層安全模
塊默認的技術選型。他可以實現強大的web安全控制。對於安全控制,我們僅
需引入spring-boot-starter-security模塊,進行少量的配置,即可實現強大的
安全管理。
幾個類:
WebSecurityConfigurerAdapter:自定義Security策略
AuthenticationManagerBuilder:自定義認證策略
@EnableWebSecurity:開啟WebSecurity模式
• 應用程序的兩個主要區域是“認證”和“授權”(或者訪問控制)。
這兩個主要區域是Spring Security 的兩個目標。
• “認證”(Authentication),是建立一個他聲明的主體的過程(一
個“主體”一般是指用戶,設備或一些可以在你的應用程序中執行動
作的其他系統)。
• “授權”(Authorization)指確定一個主體是否允許在你的應用程序
執行一個動作的過程。為了抵達需要授權的店,主體的身份已經有認
證過程建立。
• 這個概念是通用的而不只在Spring Security中。
二、Web&安全
1. 登陸/注銷
–
HttpSecurity配置登陸、注銷功能
2. Thymeleaf提供的SpringSecurity標簽支持
– 需要引入thymeleaf-extras-springsecurity4
– sec:authentication=“name”獲得當前用戶的用戶名
– sec:authorize=“hasRole(‘ADMIN’)”當前用戶必須擁有ADMIN權限時才會顯示標簽內容
3. remember me
–
表單添加remember-me的checkbox
–
配置啟用remember-me功能
4. CSRF(Cross-site request forgery)跨站請求偽造
–
HttpSecurity啟用csrf功能,會為表單添加_csrf的值,提交攜帶來預防CSRF;
啟動類:
/**
* 1、引入SpringSecurity;
* 2、編寫SpringSecurity的配置類;
* @EnableWebSecurity extends WebSecurityConfigurerAdapter
* 3、控制請求的訪問權限:
* configure(HttpSecurity http) {
* http.authorizeRequests().antMatchers("/").permitAll()
* .antMatchers("/level1/**").hasRole("VIP1")
* }
* 4、定義認證規則:
* configure(AuthenticationManagerBuilder auth){
* auth.inMemoryAuthentication()
* .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
* }
* 5、開啟自動配置的登陸功能:
* configure(HttpSecurity http){
* http.formLogin();
* }
* 6、注銷:http.logout();
* 7、記住我:Remeberme();
*/
@SpringBootApplication
public class SpringbootSecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSecurityApplication.class, args);
}
}
controller
@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;
}
}
config
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
//定制請求的授權規則
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
//開啟自動配置的登陸功能,效果,如果沒有登陸,沒有權限就會來到登陸頁面
http.formLogin().usernameParameter("user").passwordParameter("pwd")
.loginPage("/userlogin");
//1、/login來到登陸頁
//2、重定向到/login?error表示登陸失敗
//3、更多詳細規定
//4、默認post形式的 /login代表處理登陸
//5、一但定制loginPage;那么 loginPage的post請求就是登陸
//開啟自動配置的注銷功能。
http.logout().logoutSuccessUrl("/");//注銷成功以后來到首頁
//1、訪問 /logout 表示用戶注銷,清空session
//2、注銷成功會返回 /login?logout 頁面;
//開啟記住我功能
http.rememberMe().rememberMeParameter("remeber");
//登陸成功以后,將cookie發給瀏覽器保存,以后訪問頁面帶上這個cookie,只要通過檢查就可以免登錄
//點擊注銷會刪除cookie
}
//定義認證規則
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
// .passwordEncoder(new MyPasswordEncoder())//在此處應用自定義PasswordEncoder
.withUser("zhangsan")
.password("123456")
.roles("VIP1","VIP2").and()
.withUser("lisi").password("123456").roles("VIP2","VIP3")
.and()
.withUser("wangwu").password("123456").roles("VIP1","VIP3");
}
}

welcome.html
<!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 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>
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="user"/><br>
密碼:<input name="pwd"><br/>
<input type="checkbox" name="remeber"> 記住我<br/>
<input type="submit" value="登陸">
</form>
</div>
</body>
</html>