shrio 整合springboot
-
導(dǎo)入相關(guān)的依賴
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency>
-
設(shè)計數(shù)據(jù)庫表
用戶表user表
id username password role 1 aa 123456 admin 2 bb 123456 user 角色表role表
id role 1 admin 2 user
-
shrio配置類
需要實現(xiàn)3個Bean (ShiroFilterFactoryBean食拜,SecurityManager,CustomRealm )
ShiroFilterFactoryBean配置url權(quán)限訪問
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必須設(shè)置 SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// setLoginUrl 如果不設(shè)置值素邪,默認(rèn)會自動尋找Web工程根目錄下的"/login.jsp"頁面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/notLogin");
// 設(shè)置無權(quán)限時跳轉(zhuǎn)的 url;
shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
// 設(shè)置攔截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//游客芹彬,開發(fā)權(quán)限
filterChainDefinitionMap.put("/guest/**", "anon");
//用戶,需要角色權(quán)限 “user”
filterChainDefinitionMap.put("/user/**", "roles[user]");
//管理員近零,需要角色權(quán)限 “admin”
filterChainDefinitionMap.put("/admin/**", "roles[admin]");
//開放登陸接口
filterChainDefinitionMap.put("/login", "anon");
//其余接口一律攔截
//主要這行代碼必須放在所有權(quán)限設(shè)置的最后惯退,不然會導(dǎo)致所有 url 都被攔截
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
System.out.println("Shiro攔截器工廠類注入成功");
return shiroFilterFactoryBean;
}
/**
* 注入 securityManager
*/
@Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 設(shè)置realm.
securityManager.setRealm(customRealm());
return securityManager;
}
/**
* 自定義身份認(rèn)證 realm;
* <p>
* 必須寫這個類顾孽,并加上 @Bean 注解,目的是注入 CustomRealm府框,
* 否則會影響 CustomRealm類 中其他類的依賴注入
*/
@Bean
public CustomRealm customRealm() {
return new CustomRealm();
}
}
-
shrio內(nèi)置類
Filter 解釋 anon 無參萍悴,開放權(quán)限,可以理解為匿名用戶或游客 authc 無參寓免,需要認(rèn)證 logout 無參癣诱,注銷,執(zhí)行后會直接跳轉(zhuǎn)到 shiroFilterFactoryBean.setLoginUrl();
設(shè)置的 urlauthcBasic 無參袜香,表示 httpBasic 認(rèn)證 user 無參撕予,表示必須存在用戶,當(dāng)?shù)侨氩僮鲿r不做檢查 ssl 無參蜈首,表示安全的URL請求实抡,協(xié)議為 https perms[user] 參數(shù)可寫多個,表示需要某個或某些權(quán)限才能通過欢策,多個參數(shù)時寫 perms["user, admin"]吆寨,當(dāng)有多個參數(shù)時必須每個參數(shù)都通過才算通過 roles[admin] 參數(shù)可寫多個,表示是某個或某些角色才能通過踩寇,多個參數(shù)時寫 roles["admin啄清,user"],當(dāng)有多個參數(shù)時必須每個參數(shù)都通過才算通過 rest[user] 根據(jù)請求的方法俺孙,相當(dāng)于 perms[user:method]辣卒,其中 method 為 post,get睛榄,delete 等 port[8081] 當(dāng)請求的URL端口不是8081時荣茫,跳轉(zhuǎn)到schemal://serverName:8081?queryString 其中 schmal 是協(xié)議 http 或 https 等等,serverName 是你訪問的 Host场靴,8081 是 Port 端口啡莉,queryString 是你訪問的 URL 里的 ? 后面的參數(shù) 常用的主要就是 anon,authc旨剥,user咧欣,roles,perms 等
注意:anon, authc, authcBasic, user 是第一組認(rèn)證過濾器泞边,perms, port, rest, roles, ssl 是第二組授權(quán)過濾器该押,要通過授權(quán)過濾器疗杉,就先要完成登陸認(rèn)證操作(即先要完成認(rèn)證才能前去尋找授權(quán)) 才能走第二組授權(quán)器(例如訪問需要 roles 權(quán)限的 url阵谚,如果還沒有登陸的話蚕礼,會直接跳轉(zhuǎn)到
shiroFilterFactoryBean.setLoginUrl();
設(shè)置的 url ) -
自定義realm類
我們首先要繼承 AuthorizingRealm 類來自定義我們自己的 realm 以進(jìn)行我們自定義的身份,權(quán)限認(rèn)證操作梢什。 記得要 Override 重寫 doGetAuthenticationInfo 和 doGetAuthorizationInfo 兩個方法(兩個方法名很相似奠蹬,不要搞錯)realm可以自定義配置登入驗證,權(quán)限類別導(dǎo)入
public class CustomRealm extends AuthorizingRealm { private UserMapper userMapper; @Autowired private void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } /** * 獲取身份驗證信息 * Shiro中嗡午,最終是通過 Realm 來獲取應(yīng)用程序中的用戶囤躁、角色及權(quán)限信息的。 * * @param authenticationToken 用戶身份信息 token * @return 返回封裝了用戶信息的 AuthenticationInfo 實例 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("————身份認(rèn)證方法————"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; // 從數(shù)據(jù)庫獲取對應(yīng)用戶名密碼的用戶 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()); } /** * 獲取授權(quán)信息 * * @param principalCollection * @return */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("————權(quán)限認(rèn)證————"); String username = (String) SecurityUtils.getSubject().getPrincipal(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //獲得該用戶角色 String role = userMapper.getRole(username); Set<String> set = new HashSet<>(); //需要將 role 封裝到 Set 作為 info.setRoles() 的參數(shù) set.add(role); //設(shè)置該用戶擁有的角色 info.setRoles(set); return info; } }
重寫的兩個方法分別是實現(xiàn)身份認(rèn)證以及權(quán)限認(rèn)證荔睹,shiro 中有個作登陸操作的
Subject.login()
方法狸演,當(dāng)我們把封裝了用戶名,密碼的 token 作為參數(shù)傳入僻他,便會跑進(jìn)這兩個方法里面(不一定兩個方法都會進(jìn)入)其中 doGetAuthorizationInfo 方法只有在需要權(quán)限認(rèn)證時才會進(jìn)去宵距,比如前面配置類中配置了
filterChainDefinitionMap.put("/admin/**", "roles[admin]");
的管理員角色,這時進(jìn)入 /admin 時就會進(jìn)入 doGetAuthorizationInfo 方法來檢查權(quán)限吨拗;而 doGetAuthenticationInfo 方法則是需要身份認(rèn)證時(比如前面的Subject.login()
方法)才會進(jìn)入再說下 UsernamePasswordToken 類满哪,我們可以從該對象拿到登陸時的用戶名和密碼(登陸時會使用
new UsernamePasswordToken(username, password);
),而 get 用戶名或密碼有以下幾個方法token.getUsername() //獲得用戶名 String token.getPrincipal() //獲得用戶名 Object token.getPassword() //獲得密碼 char[] token.getCredentials() //獲得密碼 Object 復(fù)制代碼
注意:有很多人會發(fā)現(xiàn)劝篷,UserMapper 等類哨鸭,接口無法通過 @Autowired 注入進(jìn)來,跑程序的時候會報 NullPointerException娇妓,網(wǎng)上說了很多諸如是 Spring 加載順序等原因像鸡,但其實有一個很重要的地方要大家注意,CustomRealm 這個類是在 shiro 配置類的
securityManager.setRealm()
方法中設(shè)置進(jìn)去的哈恰,而很多人直接寫securityManager.setRealm(new CustomRealm());
,這樣是不行的坟桅,必須要使用 @Bean 注入 MyRealm,不能直接 new 對象:@Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 設(shè)置realm. securityManager.setRealm(customRealm()); return securityManager; } @Bean public CustomRealm customRealm() { return new CustomRealm(); } 復(fù)制代碼
道理也很簡單蕊蝗,和 Controller 中調(diào)用 Service 一樣仅乓,都是 SpringBean,不能自己 new
當(dāng)然蓬戚,同樣的道理也可以這樣寫:
@Bean public SecurityManager securityManager(CustomRealm customRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 設(shè)置realm. securityManager.setRealm(customRealm); return securityManager; } 復(fù)制代碼
然后只要在 CustomRealm 類加上個類似 @Component 的注解即可
-
功能實現(xiàn)
本文的功能全部以接口返回 json 數(shù)據(jù)的方式實現(xiàn)
根據(jù) url 權(quán)限分配 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("歡迎進(jìn)入夸楣,您的身份是游客");
}
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap submitLogin() {
return resultMap.success().message("您擁有獲得該接口的信息的權(quán)限!");
}
}
普通登陸用戶
@RestController
@RequestMapping("/user")
public class UserController{
@Autowired
private final ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有用戶權(quán)限子漩,可以獲得該接口的信息豫喧!");
}
}
管理員
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private final ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有管理員權(quán)限,可以獲得該接口的信息幢泼!");
}
}
突然注意到 CustomRealm 類那里拋出了 AccountException 異常紧显,現(xiàn)在建個類進(jìn)行異常捕獲
@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());
}
}
當(dāng)然還有進(jìn)行登陸等處理的 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("您沒有權(quán)限缕棵!");
}
@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里邊創(chuàng)建一個 subject
Subject subject = SecurityUtils.getSubject();
// 在認(rèn)證提交前準(zhǔn)備 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 執(zhí)行認(rèn)證登陸
subject.login(token);
//根據(jù)權(quán)限涉兽,指定返回數(shù)據(jù)
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("權(quán)限錯誤!");
}
}