1 前言
Java EE目前比較主流的authorization和authetication的庫一個為Spring Security,另一個為apache shiro。由于之前的項目是用spring boot 和shiro + vue實現(xiàn)前后分離,shiro的文檔和使用體驗比較友好也沒有什么需要特別記錄的地方权谁,權(quán)限控制粒度可以直接精確到方法剩檀。至于Spring Security屬于Spring的全家桶系列怎么也得體驗下。筆者原先用python的flask與php的laravel進行服務(wù)端開發(fā)旺芽,權(quán)限管理在python的項目中完全是輕量級的自我實現(xiàn)沪猴,收獲良多,對于新手的建議先不要一來就上手這種設(shè)計復(fù)雜的庫运嗜,對于源碼的閱讀和設(shè)計的理解會有很多障礙壶辜,最好先自己實現(xiàn)相應(yīng)功能后再去學(xué)習(xí)Shiro與Spring Security的源碼設(shè)計。 本來不太想寫這種記錄流水文洗出,但是為了節(jié)約大家在Spring Boot + Spring Security + Thymeleaf的搭建時間士复,現(xiàn)在對搭建基礎(chǔ)框架做詳細說明图谷,相關(guān)代碼可以在Github獲取翩活。本人包含搭建流程與說明以及搭建過程中踩坑(對框架不夠理解就會踩坑)心得。如果跟隨文檔搭建過程中遇到什么問題請拉到末尾看看友情提示中有無對應(yīng)的解決辦法便贵。筆者盡量在代碼注釋中說明具體功能菠镇。
項目地址: https://github.com/alexli0707/spring_boot_security_themeleaf
2 目的
這是一個Spring Boot + Spring Security + Thymeleaf 的示例項目,我們將使用Spring Security 來進行權(quán)限控制承璃。其中/admin
和 /user
是兩個角色不同權(quán)限的訪問path利耍。
3 項目
項目配置文件就不細說,在pom.xml里盔粹,為了排除干擾隘梨,所有依賴和代碼都是最簡配置。
3.1 Spring Boot 配置
3.1.1 DefaultController
返回對應(yīng)路由請求所要訪問的模板文件舷嗡。
package com.walkerlee.example.spring_boot_security_themeleaf.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DefaultController {
@GetMapping("/")
public String home1() {
return "/home";
}
@GetMapping("/home")
public String home() {
return "/home";
}
@GetMapping("/admin")
public String admin() {
return "/admin";
}
@GetMapping("/user")
public String user() {
return "/user";
}
@GetMapping("/about")
public String about() {
return "/about";
}
@GetMapping("/login")
public String login() {
return "/login";
}
@GetMapping("/403")
public String error403() {
return "/error/403";
}
}
注意這邊用的是@Controller
不是@RestController
二者的區(qū)別可以查閱對應(yīng)文檔轴猎。
3.1.2 SpringBootSecurityThemeleafApplication
應(yīng)用啟動入口。
package com.walkerlee.example.spring_boot_security_themeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootSecurityThemeleafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSecurityThemeleafApplication.class, args);
}
}
3.2 Spring Securtiy 配置
3.2.1 SecurityConfig
繼承WebSecurityConfigurerAdapter
进萄,目前配置用戶帳號密碼角色于內(nèi)存中捻脖,在配合db存儲使用的時候需要實現(xiàn)org.springframework.security.core.userdetails.UserDetailsService
接口并作更多配置,此處先使用兩個保存在內(nèi)存中的模擬角色帳號進行登錄與角色校驗中鼠。
package com.walkerlee.example.spring_boot_security_themeleaf.security.config;
import org.springframework.beans.factory.annotation.Autowired;
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.web.access.AccessDeniedHandler;
/**
* SecurityConfig
* Description: Spring Security配置
* Author:walker lee
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
// roles admin allow to access /admin/**
// roles user allow to access /user/**
// custom 403 access denied handler
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/fonts/**").permitAll() // 允許訪問資源
.antMatchers("/", "/home", "/about").permitAll() //允許訪問這三個路由
.antMatchers("/admin/**").hasAnyRole("ADMIN") // 滿足該條件下的路由需要ROLE_ADMIN的角色
.antMatchers("/user/**").hasAnyRole("USER") // 滿足該條件下的路由需要ROLE_USER的角色
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler); //自定義異常處理
}
// create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("user").roles("USER")
.and()
.withUser("admin").password("admin").roles("ADMIN");
}
}
3.2.1 CustomAccessDeniedHandler
出現(xiàn)權(quán)限限制返回HTTP_CODE為403的時候自定義展示頁面以及內(nèi)容可婶。
package com.walkerlee.example.spring_boot_security_themeleaf.security.handler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* CustomAccessDeniedHandler
* Description: handle 403 page
* Author:walker lee
*/
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
private static Logger logger = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
Authentication auth
= SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
logger.info("User '" + auth.getName()
+ "' attempted to access the protected URL: "
+ httpServletRequest.getRequestURI());
}
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/403");
}
}
3.3 Thymeleaf + Resources + Static files
3.3.1 thymeleaf的模板文件保存在src/main/resources/templates/
文件夾中,具體使用自行g(shù)oogle官方文檔援雇,Thymeleaf可以支持前后分離的開發(fā)方式矛渴,具體玩法這邊不做過多復(fù)述,該demo工程僅使用其中的基礎(chǔ)特性惫搏,
3.3.2 Fragment
可參照官方文檔
3.3.3 Demo中fragment需要特別說明的布局--footer.html曙旭,觀察sec
標簽,這是一個與Spring Security協(xié)作比較有效的方法晶府,具體可以參照Thymeleaf extra Spring Security
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
</head>
<body>
<div th:fragment="footer">
<div class="container">
<footer>
<!-- this is footer -->
<span sec:authorize="isAuthenticated()">
| Logged user: <span sec:authentication="name"></span> |
Roles: <span sec:authentication="principal.authorities"></span> |
<a th:href="@{/logout}">Sign Out</a>
</span>
</footer>
</div>
</div>
</body>
</html>
Note
關(guān)于Spring Boot的靜態(tài)資源協(xié)議配置可以參照此處 Spring Boot Serving static content
4 運行Demo
4.1 運行命令桂躏,訪問 http://localhost:8080
$ mvn spring-boot:run
頁面
點擊1訪問管理員頁面,因為沒有登錄被阻止跳轉(zhuǎn)到登錄頁:
輸入帳號
admin
密碼admin
登錄成功后重定向到http://localhost:8080/admin
川陆。此時返回主頁進入2用戶頁面剂习,提示403沒有對應(yīng)權(quán)限:最終點擊登出重定向到:
http://localhost:8080/login?logout
,到此快速模板算是搭建完畢,如果需要更多深入的詳解和展開這個篇幅肯定是不夠的鳞绕,先到這里失仁。
Tip:聊下可能會遇到的問題
- 無法啟動項目(如果用的是github上的工程項目肯定是不會的),如果是自己搭建的話可能是沒有在pom配置 :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>- 登錄成功后重定向到你的css文件或者js文件而不是上一次訪問的路徑们何? 很有可能是沒有配置允許資源文件被外網(wǎng)訪問的權(quán)限萄焦,導(dǎo)致登錄成功的回調(diào)handler中request的referer是被提示403的資源文件。
- 如果需要針對結(jié)合數(shù)據(jù)庫以及更多功能的快速集成的話歡迎留個言冤竹,元旦有時間也會一并寫下拂封。
引用:
- Securing a Web Application
- Spring Security Reference
- Spring Boot Security features
- Spring Boot Hello World Example – Thymeleaf
- Spring Security Hello World Annotation Example
- Thymeleaf – Spring Security integration basics
- Thymeleaf extra – Spring Security integration basics
- Thymeleaf – Standard URL Syntax
- Spring Boot + Spring MVC + Spring Security + MySQL
- Spring Boot – Static content
- Spring Boot Spring security themeleaf example