我也是半路出家的人,若是你們有什麼好的意見或批評,請務必issue
下。php
項目地址:github.com/Smith-Cruis… 。html
若是想要直接體驗,直接clone
項目,運行mvn spring-boot:run
命令便可進行訪問。網址規則自行看教程後面。java
若是想了解Spring Security能夠看git
Spring Boot 2.0+Srping Security+Thymeleaf的簡易教程github
Spring Boot 2 + Spring Security 5 + JWT 的單頁應用Restful解決方案web
在開始本教程以前,請保證已經熟悉如下幾點。spring
Controller
、RestController
、Autowired
等這些基本註釋。其實看看官方的Getting-Start教程就差很少了。簡要的說明下咱們爲何要用JWT,由於咱們要實現徹底的先後端分離,因此不可能使用session
,cookie
的方式進行鑑權,因此JWT就被派上了用場,你能夠經過一個加密密鑰來進行先後端的鑑權。數據庫
/login
進行登入,若是成功返回一個加密token,失敗的話直接返回401錯誤。header
中添加Authorization
字段,例如Authorization: token
,token
爲密鑰。token
的校驗,若是有誤會直接返回401。username
信息在token中。token
進行加密。token
中攜帶的username
信息。token
是否正確。新建一個Maven工程,添加相關的dependencies。apache
<?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>org.inlighting</groupId> <artifactId>shiro-study</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.8.RELEASE</version> </dependency> </dependencies> <build> <plugins> <!-- Srping Boot 打包工具 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.5.7.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <!-- 指定JDK編譯版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project> 複製代碼
注意指定JDK版本和編碼後端
爲了縮減教程的代碼,我使用HashMap
本地模擬了一個數據庫,結構以下
username | password | role | permission |
---|---|---|---|
smith | smith123 | user | view |
danny | danny123 | admin | view,edit |
這是一個最簡單的用戶權限表,若是想更加進一步瞭解,自行百度RBAC。
以後再構建一個UserService
來模擬數據庫查詢,而且把結果放到UserBean
之中。
@Component public class UserService { public UserBean getUser(String username) { // 沒有此用戶直接返回null if (! DataSource.getData().containsKey(username)) return null; UserBean user = new UserBean(); Map<String, String> detail = DataSource.getData().get(username); user.setUsername(username); user.setPassword(detail.get("password")); user.setRole(detail.get("role")); user.setPermission(detail.get("permission")); return user; } } 複製代碼
public class UserBean { private String username; private String password; private String role; private String permission; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } } 複製代碼
咱們寫一個簡單的JWT加密,校驗工具,而且使用用戶本身的密碼充當加密密鑰,這樣保證了token 即便被他人截獲也沒法破解。而且咱們在token
中附帶了username
信息,而且設置密鑰5分鐘就會過時。
public class JWTUtil { // 過時時間5分鐘 private static final long EXPIRE_TIME = 5*60*1000; /** * 校驗token是否正確 * @param token 密鑰 * @param secret 用戶的密碼 * @return 是否正確 */ public static boolean verify(String token, String username, String secret) { try { Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username) .build(); DecodedJWT jwt = verifier.verify(token); return true; } catch (Exception exception) { return false; } } /** * 得到token中的信息無需secret解密也能得到 * @return token中包含的用戶名 */ public static String getUsername(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { return null; } } /** * 生成簽名,5min後過時 * @param username 用戶名 * @param secret 用戶的密碼 * @return 加密的token */ public static String sign(String username, String secret) { try { Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附帶username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } catch (UnsupportedEncodingException e) { return null; } } } 複製代碼
既然想要實現restful,那咱們要保證每次返回的格式都是相同的,所以我創建了一個ResponseBean
來統一返回的格式。
public class ResponseBean { // http 狀態碼 private int code; // 返回信息 private String msg; // 返回的數據 private Object data; public ResponseBean(int code, String msg, Object data) { this.code = code; this.msg = msg; this.data = data; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } } 複製代碼
爲了實現我本身可以手動拋出異常,我本身寫了一個UnauthorizedException.java
public class UnauthorizedException extends RuntimeException { public UnauthorizedException(String msg) { super(msg); } public UnauthorizedException() { super(); } } 複製代碼
URL | 做用 |
---|---|
/login | 登入 |
/article | 全部人均可以訪問,可是用戶與遊客看到的內容不一樣 |
/require_auth | 登入的用戶才能夠進行訪問 |
/require_role | admin的角色用戶才能夠登入 |
/require_permission | 擁有view和edit權限的用戶才能夠訪問 |
@RestController public class WebController { private static final Logger LOGGER = LogManager.getLogger(WebController.class); private UserService userService; @Autowired public void setService(UserService userService) { this.userService = userService; } @PostMapping("/login") public ResponseBean login(@RequestParam("username") String username, @RequestParam("password") String password) { UserBean userBean = userService.getUser(username); if (userBean.getPassword().equals(password)) { return new ResponseBean(200, "Login success", JWTUtil.sign(username, password)); } else { throw new UnauthorizedException(); } } @GetMapping("/article") public ResponseBean article() { Subject subject = SecurityUtils.getSubject(); if (subject.isAuthenticated()) { return new ResponseBean(200, "You are already logged in", null); } else { return new ResponseBean(200, "You are guest", null); } } @GetMapping("/require_auth") @RequiresAuthentication public ResponseBean requireAuth() { return new ResponseBean(200, "You are authenticated", null); } @GetMapping("/require_role") @RequiresRoles("admin") public ResponseBean requireRole() { return new ResponseBean(200, "You are visiting require_role", null); } @GetMapping("/require_permission") @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"}) public ResponseBean requirePermission() { return new ResponseBean(200, "You are visiting permission require edit,view", null); } @RequestMapping(path = "/401") @ResponseStatus(HttpStatus.UNAUTHORIZED) public ResponseBean unauthorized() { return new ResponseBean(401, "Unauthorized", null); } } 複製代碼
以前說過restful要統一返回的格式,因此咱們也要全局處理Spring Boot
的拋出異常。利用@RestControllerAdvice
能很好的實現。
@RestControllerAdvice public class ExceptionController { // 捕捉shiro的異常 @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(ShiroException.class) public ResponseBean handle401(ShiroException e) { return new ResponseBean(401, e.getMessage(), null); } // 捕捉UnauthorizedException @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) public ResponseBean handle401() { return new ResponseBean(401, "Unauthorized", null); } // 捕捉其餘全部異常 @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseBean globalException(HttpServletRequest request, Throwable ex) { return new ResponseBean(getStatus(request).value(), ex.getMessage(), null); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } } 複製代碼
你們能夠先看下官方的 Spring-Shiro 整合教程,有個初步的瞭解。不過既然咱們用了Spring-Boot
,那咱們確定要爭取零配置文件。
JWTToken
差很少就是Shiro
用戶名密碼的載體。由於咱們是先後端分離,服務器無需保存用戶狀態,因此不須要RememberMe
這類功能,咱們簡單的實現下AuthenticationToken
接口便可。由於token
本身已經包含了用戶名等信息,因此這裏我就弄了一個字段。若是你喜歡鑽研,能夠看看官方的UsernamePasswordToken
是如何實現的。
public class JWTToken implements AuthenticationToken { // 密鑰 private String token; public JWTToken(String token) { this.token = token; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return token; } } 複製代碼
realm
的用於處理用戶是否合法的這一塊,須要咱們本身實現。
@Service public class MyRealm extends AuthorizingRealm { private static final Logger LOGGER = LogManager.getLogger(MyRealm.class); private UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; } /** * 大坑!,必須重寫此方法,否則Shiro會報錯 */ @Override public boolean supports(AuthenticationToken token) { return token instanceof JWTToken; } /** * 只有當須要檢測用戶權限的時候纔會調用此方法,例如checkRole,checkPermission之類的 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = JWTUtil.getUsername(principals.toString()); UserBean user = userService.getUser(username); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); simpleAuthorizationInfo.addRole(user.getRole()); Set<String> permission = new HashSet<>(Arrays.asList(user.getPermission().split(","))); simpleAuthorizationInfo.addStringPermissions(permission); return simpleAuthorizationInfo; } /** * 默認使用此方法進行用戶名正確與否驗證,錯誤拋出異常便可。 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException { String token = (String) auth.getCredentials(); // 解密得到username,用於和數據庫進行對比 String username = JWTUtil.getUsername(token); if (username == null) { throw new AuthenticationException("token invalid"); } UserBean userBean = userService.getUser(username); if (userBean == null) { throw new AuthenticationException("User didn't existed!"); } if (! JWTUtil.verify(token, username, userBean.getPassword())) { throw new AuthenticationException("Username or password error"); } return new SimpleAuthenticationInfo(token, token, "my_realm"); } } 複製代碼
在doGetAuthenticationInfo
中用戶能夠自定義拋出不少異常,詳情見文檔。
全部的請求都會先通過Filter
,因此咱們繼承官方的BasicHttpAuthenticationFilter
,而且重寫鑑權的方法。
代碼的執行流程preHandle
->isAccessAllowed
->isLoginAttempt
->executeLogin
public class JWTFilter extends BasicHttpAuthenticationFilter { private Logger LOGGER = LoggerFactory.getLogger(this.getClass()); /** * 判斷用戶是否想要登入。 * 檢測header裏面是否包含Authorization字段便可 */ @Override protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) { HttpServletRequest req = (HttpServletRequest) request; String authorization = req.getHeader("Authorization"); return authorization != null; } /** * */ @Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String authorization = httpServletRequest.getHeader("Authorization"); JWTToken token = new JWTToken(authorization); // 提交給realm進行登入,若是錯誤他會拋出異常並被捕獲 getSubject(request, response).login(token); // 若是沒有拋出異常則表明登入成功,返回true return true; } /** * 這裏咱們詳細說明下爲何最終返回的都是true,即容許訪問 * 例如咱們提供一個地址 GET /article * 登入用戶和遊客看到的內容是不一樣的 * 若是在這裏返回了false,請求會被直接攔截,用戶看不到任何東西 * 因此咱們在這裏返回true,Controller中能夠經過 subject.isAuthenticated() 來判斷用戶是否登入 * 若是有些資源只有登入用戶才能訪問,咱們只須要在方法上面加上 @RequiresAuthentication 註解便可 * 可是這樣作有一個缺點,就是不可以對GET,POST等請求進行分別過濾鑑權(由於咱們重寫了官方的方法),但實際上對應用影響不大 */ @Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { if (isLoginAttempt(request, response)) { try { executeLogin(request, response); } catch (Exception e) { response401(request, response); } } return true; } /** * 對跨域提供支持 */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE"); httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers")); // 跨域時會首先發送一個option請求,這裏咱們給option請求直接返回正常狀態 if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) { httpServletResponse.setStatus(HttpStatus.OK.value()); return false; } return super.preHandle(request, response); } /** * 將非法請求跳轉到 /401 */ private void response401(ServletRequest req, ServletResponse resp) { try { HttpServletResponse httpServletResponse = (HttpServletResponse) resp; httpServletResponse.sendRedirect("/401"); } catch (IOException e) { LOGGER.error(e.getMessage()); } } } 複製代碼
getSubject(request, response).login(token);
這一步就是提交給了realm
進行處理
@Configuration public class ShiroConfig { @Bean("securityManager") public DefaultWebSecurityManager getManager(MyRealm realm) { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); // 使用本身的realm manager.setRealm(realm); /* * 關閉shiro自帶的session,詳情見文檔 * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29 */ DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator(); defaultSessionStorageEvaluator.setSessionStorageEnabled(false); subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator); manager.setSubjectDAO(subjectDAO); return manager; } @Bean("shiroFilter") public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); // 添加本身的過濾器而且取名爲jwt Map<String, Filter> filterMap = new HashMap<>(); filterMap.put("jwt", new JWTFilter()); factoryBean.setFilters(filterMap); factoryBean.setSecurityManager(securityManager); factoryBean.setUnauthorizedUrl("/401"); /* * 自定義url規則 * http://shiro.apache.org/web.html#urls- */ Map<String, String> filterRuleMap = new HashMap<>(); // 全部請求經過咱們本身的JWT Filter filterRuleMap.put("/**", "jwt"); // 訪問401和404頁面不經過咱們的Filter filterRuleMap.put("/401", "anon"); factoryBean.setFilterChainDefinitionMap(filterRuleMap); return factoryBean; } /** * 下面的代碼是添加註解支持 */ @Bean @DependsOn("lifecycleBeanPostProcessor") public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator(); // 強制使用cglib,防止重複代理和可能引發代理出錯的問題 // https://zhuanlan.zhihu.com/p/29161098 defaultAdvisorAutoProxyCreator.setProxyTargetClass(true); return defaultAdvisorAutoProxyCreator; } @Bean public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { return new LifecycleBeanPostProcessor(); } @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); advisor.setSecurityManager(securityManager); return advisor; } } 複製代碼
裏面URL規則本身參考文檔便可http://shiro.apache.org/web.html 。
我就說下代碼還有哪些能夠進步的地方吧
Cache
功能。/401
地址實現。