SpringBoot整合Shiro
Apache Shiro
? ? ? ?Apache Shiro是一個功能強大事镣、靈活的蛮浑,開源的安全框架。它可以干凈利落地處理身份驗證沮稚、授權(quán)蕴掏、企業(yè)會話管理和加密。
Apache Shiro的首要目標(biāo)是易于使用和理解挽荡。安全通常很復(fù)雜即供,甚至讓人感到很痛苦,但是Shiro卻不是這樣子的青自。一個好的安全框架應(yīng)該屏蔽復(fù)雜性驱证,向外暴露簡單、直觀的API逆瑞,來簡化開發(fā)人員實現(xiàn)應(yīng)用程序安全所花費的時間和精力。
Shiro能做什么呢哈肖?
- 驗證用戶身份
- 用戶訪問權(quán)限控制谋减,比如:1出爹、判斷用戶是否分配了一定的安全角色。2总寻、判斷用戶是否被授予完成某個操作的權(quán)限
- 在非 web 或 EJB 容器的環(huán)境下可以任意使用Session API
- 可以響應(yīng)認證梢为、訪問控制,或者 Session 生命周期中發(fā)生的事件
- 可將一個或以上用戶安全數(shù)據(jù)源數(shù)據(jù)組合成一個復(fù)合的用戶 “view”(視圖)
- 支持單點登錄(SSO)功能
- 支持提供“Remember Me”服務(wù)祟印,獲取用戶關(guān)聯(lián)信息而無需登錄
快速上手
先貼上pom.xml文件
<dependencies>
<!--自動配置支持蕴忆、日志和YAML-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--JUnit悲幅、Hamcrest、Mockito-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- druid數(shù)據(jù)源驅(qū)動 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
配置好自己的application.properties文件
-
創(chuàng)建數(shù)據(jù)庫
- 我們在這里創(chuàng)建一個user表
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `role` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` (`id`, `username`, `password`, `role`) VALUES (1,'jmtang','1234','admin'), (2,'zhangsan','12345','user'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES;
-
開始配置Shiro
- 需要配置shiroconfig文件
- 根據(jù)ShiroConfig的配置,將相應(yīng)的URL加載到Shiro框架中
- 用戶執(zhí)行登錄時吟孙,會自動執(zhí)行doGetAuthenticationInfo和doGetAuthorizationInfo方法進行認證和鑒權(quán)
- 用戶進行訪問操作存谎,若無權(quán)限或者未登錄既荚,會根據(jù)shiroConfig的配置栋艳,自動跳轉(zhuǎn)到相應(yīng)頁面
- 使用用戶賬戶名和密碼生成令牌---->執(zhí)行登錄(shiro本身并不知令牌是否合法,通過用戶自行實現(xiàn)Realm進行比對,常用的是數(shù)據(jù)庫查詢)
注意:這里面有個坑:SecurityManager導(dǎo)入的包應(yīng)該來源與org.apache.shiro.mgt.SecurityManager
- 需要配置shiroconfig文件
@Configuration
public class shiroconfig {
/**
* 主要配置一些相應(yīng)的URL的規(guī)則和訪問權(quán)限
* @param securityManager
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必須設(shè)置SecurityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
// setLoginUrl 如果不設(shè)置值糙置,默認會自動尋找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;
}
/**
* 自定義身份認證 realm;
* <p>
* 必須寫這個類哈雏,并加上 @Bean 注解,目的是注入 CustomRealm土浸,
* 否則會影響 CustomRealm類 中其他類的依賴注入
*/
@Bean
public CustomRealm customRealm() {
return new CustomRealm();
}
}
Filter Chain說明
- 一個URL可以配置多個Filter彭羹,使用逗號分隔
- 當(dāng)設(shè)置多個過濾器時,全部驗證通過毅舆,才視為通過
- 部分過濾器可指定參數(shù)愈腾,如perms,roles
Shiro內(nèi)置的FilterChain悦即,這里面舉出幾個常見的的FilterChain
- anon: 所有url都都可以匿名訪問
- authc: 需要認證才能進行訪問
- roles: 參數(shù)可寫多個橱乱,表示是某個或某些角色才能通過,多個參數(shù)時寫 roles["admin作瞄,user"]危纫,當(dāng)有多個參數(shù)時必須每個參數(shù)都通過才算通過
- user: 配置記住我或認證通過可以訪問
- perms:參數(shù)可寫多個,表示需要某個或某些權(quán)限才能通過契耿,多個參數(shù)時寫 perms["user, admin"],當(dāng)有多個參數(shù)時必須每個參數(shù)都通過才算通過
Shiro 開始實現(xiàn)兩個方面
- 登陸認證實現(xiàn)
- 權(quán)限管理實現(xiàn)
登陸認證實現(xiàn)
- 檢查提交的進行認證的令牌信息
- 根據(jù)令牌信息從數(shù)據(jù)源(通常為數(shù)據(jù)庫)中獲取用戶信息
- 對用戶信息進行匹配驗證透敌。
- 驗證通過將返回一個封裝了用戶信息的AuthenticationInfo實例酗电。
- 驗證失敗則拋出AuthenticationException異常信息裸燎。
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("————身份認證方法————");
// 獲取用戶的Token
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 根據(jù)Token中的username
// 從數(shù)據(jù)庫獲取對應(yīng)用戶名密碼的用戶
String password = userDao.getPassword(token.getUsername());
if (null == password) {
throw new AccountException("用戶名不正確");
} else if (!password.equals(new String((char[]) token.getCredentials()))) {
throw new AccountException("密碼不正確");
}
// 最終會封裝到一個AuthenticationInfo類中
return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
}
權(quán)限管理的實現(xiàn)
- 獲取身份驗證信息
- Shiro中 通過 Realm 來獲取應(yīng)用程序中的用戶德绿、角色及權(quán)限信息的。
- 當(dāng)訪問到頁面的時候移稳,鏈接配置了相應(yīng)的權(quán)限或者shiro標(biāo)簽才會執(zhí)行此方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("————權(quán)限認證————");
// 獲取用戶的輸入賬號
String username = (String) SecurityUtils.getSubject().getPrincipal();
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//獲得該用戶角色
String role = userDao.getRole(username);
Set<String> set = new HashSet<>();
//需要將 role 封裝到 Set 作為 info.setRoles() 的參數(shù)
set.add(role);
//設(shè)置該用戶擁有的角色
info.setRoles(set);
return info;
}
接下來就是將URL權(quán)限分配給Controller
主要有:
- AdminController
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有管理員權(quán)限个粱,可以獲得該接口的信息都许!");
}
}
- ExceptionContrller
@RestControllerAdvice
public class ExceptionController {
private 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());
}
}
- GuestController
@RestController
@RequestMapping("/guest")
public class GuestController {
@Autowired
private 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("您擁有獲得該接口的信息的權(quán)限塞椎!");
}
}
- LoginController
@RestController
public class LoginController {
@Autowired
private ResultMap resultMap;
@Autowired
private UserDao userDao;
@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();
// 在認證提交前準(zhǔn)備 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 執(zhí)行認證登陸
subject.login(token);
//根據(jù)權(quán)限拉庵,指定返回數(shù)據(jù)
String role = userDao.getRole(username);
if ("user".equals(role)) {
return resultMap.success().message("歡迎登陸");
}
if ("admin".equals(role)) {
return resultMap.success().message("歡迎來到管理員頁面");
}
return resultMap.fail().message("權(quán)限錯誤名段!");
}
}
- UserController
@RestController
@RequestMapping("/user")
public class UserController{
@Autowired
private ResultMap resultMap;
@RequestMapping(value = "/getMessage", method = RequestMethod.GET)
public ResultMap getMessage() {
return resultMap.success().message("您擁有用戶權(quán)限泣懊,可以獲得該接口的信息!");
}
}
到此就可以用POSTMAN測試了,還沒使用前后端分離連接起來信夫,敬請期待?▎!振湾!
參考: