教你 Shiro 整合 SpringBoot,避開各種坑

最近搞了下 Shiro 安全框架,找了一些網上的博客文章,但是一到自己實現的時候就遇到了各種坑,需要各種查資料看源碼以及各種測試。 那麼這篇文章就教大家如何將 Shiro 整合到 SpringBoot 中,並避開一些小坑,這次實現了基本的登陸以及角色權限。

附上源碼:github.com/HowieYuan/s…

依賴包


org.apache.shiro
shiro-spring
1.3.2

複製代碼

數據庫表

一切從簡,用戶 user 表,以及角色 role 表

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

Shiro 相關類

Shiro 配置類

@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必須設置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// setLoginUrl 如果不設置值,默認會自動尋找Web工程根目錄下的"/login.jsp"頁面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/notLogin");
// 設置無權限時跳轉的 url;
shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
// 設置攔截器
Map filterChainDefinitionMap = new LinkedHashMap<>();
//遊客,開發權限
filterChainDefinitionMap.put("/guest/**", "anon");
//用戶,需要角色權限 “user”
filterChainDefinitionMap.put("/user/**", "roles[user]");
//管理員,需要角色權限 “admin”
filterChainDefinitionMap.put("/admin/**", "roles[admin]");
//開放登陸接口
filterChainDefinitionMap.put("/login", "anon");
//其餘接口一律攔截
//主要這行代碼必須放在所有權限設置的最後,不然會導致所有 url 都被攔截
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
System.out.println("Shiro攔截器工廠類注入成功");
return shiroFilterFactoryBean;
}
/**
* 注入 securityManager

*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 設置realm.
securityManager.setRealm(customRealm());
return securityManager;
}
/**
* 自定義身份認證 realm;
*


* 必須寫這個類,並加上 @Bean 註解,目的是注入 CustomRealm,
* 否則會影響 CustomRealm類 中其他類的依賴注入
*/
@Bean
public CustomRealm customRealm() {
return new CustomRealm();
}
}

注意:裡面的 SecurityManager 類導入的應該是 import org.apache.shiro.mgt.SecurityManager; 但是,如果你是複製代碼過來的話,會默認導入 java.lang.SecurityManager 這裡也稍稍有點坑,其他的類的話,也是都屬於 shiro 包裡面的類

shirFilter 方法中主要是設置了一些重要的跳轉 url,比如未登陸時,無權限時的跳轉;以及設置了各類 url 的權限攔截,比如 /user 開始的 url 需要 user 權限,/admin 開始的 url 需要 admin 權限等

權限攔截 Filter

當運行一個Web應用程序時,Shiro將會創建一些有用的默認 Filter 實例,並自動地將它們置為可用,而這些默認的 Filter 實例是被 DefaultFilter 枚舉類定義的,當然我們也可以自定義 Filter 實例,這些在以後的文章中會講到

教你 Shiro 整合 SpringBoot,避開各種坑

Filter解釋anon無參,開放權限,可以理解為匿名用戶或遊客authc無參,需要認證logout無參,註銷,執行後會直接跳轉到shiroFilterFactoryBean.setLoginUrl(); 設置的 urlauthcBasic無參,表示 httpBasic 認證user無參,表示必須存在用戶,當登入操作時不做檢查ssl無參,表示安全的URL請求,協議為 httpsperms[user]參數可寫多個,表示需要某個或某些權限才能通過,多個參數時寫 perms["user, admin"],當有多個參數時必須每個參數都通過才算通過roles[admin]參數可寫多個,表示是某個或某些角色才能通過,多個參數時寫 roles["admin,user"],當有多個參數時必須每個參數都通過才算通過rest[user]根據請求的方法,相當於 perms[user:method],其中 method 為 post,get,delete 等port[8081]當請求的URL端口不是8081時,跳轉到schemal://serverName:8081?queryString 其中 schmal 是協議 http 或 https 等等,serverName 是你訪問的 Host,8081 是 Port 端口,queryString 是你訪問的 URL 裡的 ? 後面的參數

常用的主要就是 anon,authc,user,roles,perms 等

注意:anon, authc, authcBasic, user 是第一組認證過濾器,perms, port, rest, roles, ssl 是第二組授權過濾器,要通過授權過濾器,就先要完成登陸認證操作(即先要完成認證才能前去尋找授權) 才能走第二組授權器(例如訪問需要 roles 權限的 url,如果還沒有登陸的話,會直接跳轉到 shiroFilterFactoryBean.setLoginUrl(); 設置的 url )

自定義 realm 類

我們首先要繼承 AuthorizingRealm 類來自定義我們自己的 realm 以進行我們自定義的身份,權限認證操作。 記得要 Override 重寫 doGetAuthenticationInfo 和 doGetAuthorizationInfo 兩個方法(兩個方法名很相似,不要搞錯)

public class CustomRealm extends AuthorizingRealm {
private UserMapper userMapper;
@Autowired
private void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
/**
* 獲取身份驗證信息
* Shiro中,最終是通過 Realm 來獲取應用程序中的用戶、角色及權限信息的。
*
* @param authenticationToken 用戶身份信息 token
* @return 返回封裝了用戶信息的 AuthenticationInfo 實例
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("————身份認證方法————");

UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 從數據庫獲取對應用戶名密碼的用戶
String password = userMapper.getPassword(token.getUsername());
if (null == password) {
throw new AccountException("用戶名不正確");
} else if (!password.equals(new String((char[]) token.getCredentials()))) {
throw new AccountException("密碼不正確");
}
return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
}
/**
* 獲取授權信息
*
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("————權限認證————");
String username = (String) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//獲得該用戶角色
String role = userMapper.getRole(username);
Set set = new HashSet<>();
//需要將 role 封裝到 Set 作為 info.setRoles() 的參數
set.add(role);
//設置該用戶擁有的角色
info.setRoles(set);
return info;
}
}

重寫的兩個方法分別是實現身份認證以及權限認證,shiro 中有個作登陸操作的 Subject.login()方法,當我們把封裝了用戶名,密碼的 token 作為參數傳入,便會跑進這兩個方法裡面(不一定兩個方法都會進入)

其中 doGetAuthorizationInfo 方法只有在需要權限認證時才會進去,比如前面配置類中配置了 filterChainDefinitionMap.put("/admin/**", "roles[admin]"); 的管理員角色,這時進入 /admin 時就會進入 doGetAuthorizationInfo 方法來檢查權限;而 doGetAuthenticationInfo 方法則是需要身份認證時(比如前面的 Subject.login() 方法)才會進入

再說下 UsernamePasswordToken 類,我們可以從該對象拿到登陸時的用戶名和密碼(登陸時會使用 new UsernamePasswordToken(username, password);),而 get 用戶名或密碼有以下幾個方法

token.getUsername() //獲得用戶名 String
token.getPrincipal() //獲得用戶名 Object
token.getPassword() //獲得密碼 char[]
token.getCredentials() //獲得密碼 Object

注意:有很多人會發現,UserMapper 等類,接口無法通過 @Autowired 注入進來,跑程序的時候會報 NullPointerException,網上說了很多諸如是 Spring 加載順序等原因,但其實有一個很重要的地方要大家注意,CustomRealm 這個類是在 shiro 配置類的 securityManager.setRealm()方法中設置進去的,而很多人直接寫securityManager.setRealm(new CustomRealm()); ,這樣是不行的,必須要使用 @Bean 注入 MyRealm,不能直接 new 對象:

 @Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 設置realm.
securityManager.setRealm(customRealm());
return securityManager;
}
@Bean
public CustomRealm customRealm() {

return new CustomRealm();
}

道理也很簡單,和 Controller 中調用 Service 一樣,都是 SpringBean,不能自己 new

當然,同樣的道理也可以這樣寫:

 @Bean
public SecurityManager securityManager(CustomRealm customRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 設置realm.
securityManager.setRealm(customRealm);
return securityManager;
}

然後只要在 CustomRealm 類加上個類似 @Component 的註解即可

功能實現

本文的功能全部以接口返回 json 數據的方式實現

根據 url 權限分配 controller

遊客
@RestController
@RequestMapping("/guest")
public class GuestController{
@Autowired
private final ResultMap resultMap;
@RequestMapping(value = "/enter", method = RequestMethod.GET)
public ResultMap login() {
return resultMap.success().message("歡迎進入,您的身份是遊客");
}
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap submitLogin() {
return resultMap.success().message("您擁有獲得該接口的信息的權限!");
}

}
普通登陸用戶
@RestController
@RequestMapping("/user")
public class UserController{
@Autowired
private final ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有用戶權限,可以獲得該接口的信息!");
}
}
管理員
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private final ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有管理員權限,可以獲得該接口的信息!");
}
}

突然注意到 CustomRealm 類那裡拋出了 AccountException 異常,現在建個類進行異常捕獲

@RestControllerAdvice
public class ExceptionController {
private final ResultMap resultMap;
@Autowired
public ExceptionController(ResultMap resultMap) {
this.resultMap = resultMap;
}
// 捕捉 CustomRealm 拋出的異常
@ExceptionHandler(AccountException.class)
public ResultMap handleShiroException(Exception ex) {
return resultMap.fail().message(ex.getMessage());
}
}

當然還有進行登陸等處理的 LoginController

@RestController
public class LoginController {
@Autowired
private ResultMap resultMap;
private UserMapper userMapper;
@RequestMapping(value = "/notLogin", method = RequestMethod.GET)
public ResultMap notLogin() {
return resultMap.success().message("您尚未登陸!");
}
@RequestMapping(value = "/notRole", method = RequestMethod.GET)
public ResultMap notRole() {
return resultMap.success().message("您沒有權限!");
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public ResultMap logout() {
Subject subject = SecurityUtils.getSubject();
//註銷
subject.logout();
return resultMap.success().message("成功註銷!");
}
/**
* 登陸
*
* @param username 用戶名
* @param password 密碼
*/
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResultMap login(String username, String password) {
// 從SecurityUtils裡邊創建一個 subject
Subject subject = SecurityUtils.getSubject();
// 在認證提交前準備 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 執行認證登陸
subject.login(token);
//根據權限,指定返回數據
String role = userMapper.getRole(username);
if ("user".equals(role)) {
return resultMap.success().message("歡迎登陸");
}
if ("admin".equals(role)) {
return resultMap.success().message("歡迎來到管理員頁面");
}

return resultMap.fail().message("權限錯誤!");
}
}

測試

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

教你 Shiro 整合 SpringBoot,避開各種坑

現在私信我“資料”即可獲取Java工程化、高性能及分佈式、高性能、高架構。性能調優、Spring,MyBatis,Netty源碼分析和大數據等多個知識點高級進階乾貨的直播免費學習權限及領取相關免費資料


分享到:


相關文章: