SpringBoot中的Shiro及環(huán)境搭建
什么是Shiro?
一個(gè)Java的安全(權(quán)限)框架,可以完成認(rèn)證、授權(quán)、加密、會(huì)話管理、Web集成、緩存等
下載地址:Apache Shiro | Simple. Java. Security.

快速啟動(dòng)
先在官網(wǎng)找到入門(mén)案例:shiro/samples/quickstart at main · apache/shiro · GitHub
步驟:
1、新建一個(gè) Maven 工程,刪除其 src 目錄,將其作為父工程
2、在父工程中新建一個(gè) Maven 模塊
3、在maven模塊中,復(fù)制依賴(lài)
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.24</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>4、復(fù)制 log4j.properties
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries log4j.logger.org.apache=WARN # Spring log4j.logger.org.springframework=WARN # Default Shiro logging log4j.logger.org.apache.shiro=INFO # Disable verbose logging log4j.logger.org.apache.shiro.util.ThreadContext=WARN log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
5、復(fù)制 shiro.ini(要先在 IDEA中添加 ini 插件)
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle56、復(fù)制 Quickstart
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @ClassName Quickstart
* @Description TODO
* @Author GuoSheng
* @Date 2021/4/20 17:28
* @Version 1.0
**/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured
// realms, users, roles and permissions is to use the simple INI config.
// We'll do that by using a factory that can ingest a .ini file and
// return a SecurityManager instance:
// Use the shiro.ini file at the root of the classpath
// (file: and url: prefixes load from files and urls respectively):
DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
IniRealm iniRealm=new IniRealm("classpath:shiro.ini");
defaultSecurityManager.setRealm(iniRealm);
// for this simple example quickstart, make the SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this
// and instead rely on their container configuration or web.xml for
// webapps. That is outside the scope of this simple quickstart, so
// we'll just do the bare minimum so you can continue to get a feel
// for things.
SecurityUtils.setSecurityManager(defaultSecurityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//all done - log out!
currentUser.logout();
System.exit(0);
}
}7、運(yùn)行結(jié)果

Shiro的Subject分析
Quickstart 中的一些方法:
1、獲取當(dāng)前用戶
Subject currentUser = SecurityUtils.getSubject();
2、通過(guò)當(dāng)前用戶拿到 Session
Session session = currentUser.getSession();
3、用session存值取值
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");4、判斷是否被認(rèn)證
currentUser.isAuthenticated()
5、執(zhí)行登錄操作
currentUser.login(token);
6、打印其標(biāo)識(shí)主體
currentUser.getPrincipal()
7、判斷當(dāng)前用戶是否有某個(gè)角色
currentUser.hasRole("schwartz")8、注銷(xiāo)
currentUser.logout();
SpringBoot整合Shiro環(huán)境搭建
步驟:
1、導(dǎo)入shiro的整合依賴(lài)
<!--shiro整合spring-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>2、在config包下,編寫(xiě)Shiro的配置類(lèi)
①自定義 Realm 類(lèi)
public class UserRealm extends AuthorizingRealm {
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了shiro的授權(quán)方法");
return null;
}
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("執(zhí)行了shiro的認(rèn)證方法");
return null;
}
}②自定義 ShiroConfig
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關(guān)聯(lián) UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//創(chuàng)建Realm對(duì)象,需要自定義類(lèi)
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}Shiro實(shí)現(xiàn)登錄攔截
功能:必須認(rèn)證了才能訪問(wèn)add和update頁(yè)面,沒(méi)有認(rèn)證直接跳到登錄頁(yè)面
步驟:
1、編寫(xiě)前端頁(yè)面
①編寫(xiě)首頁(yè)
<h1>首頁(yè)</h1>
②編寫(xiě)測(cè)試頁(yè)
(登錄首頁(yè)的時(shí)候,通過(guò)controller跳到測(cè)試頁(yè),測(cè)試頁(yè)包含可以跳到add和update頁(yè)面的超鏈接)
<h1>測(cè)試頁(yè)</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" >add</a>
<a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" >update</a>③add頁(yè)面
<h1>add</h1> 增加一個(gè)用戶
④update頁(yè)面
<h1>update</h1> 修改一個(gè)用戶
⑤登錄頁(yè)
<h1>登錄</h1>
<form action="toLogin">
用戶名:<input type="text" name="username"> <br>
密碼: <input type="password" name="password"> <br>
<button type="submit">提交</button>
</form>2、編寫(xiě)Controller
@Controller
public class MyController {
@RequestMapping({"/","/index","/index.html"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "test";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
}3、shiro配置登錄攔截
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//設(shè)置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的內(nèi)置過(guò)濾器
/*
anon:無(wú)需認(rèn)證就可以訪問(wèn)
authc:必須認(rèn)證了才能訪問(wèn)
user:必須擁有 記住我 功能才能訪問(wèn)
perms:擁有某個(gè)權(quán)限才能訪問(wèn)
role:擁有某個(gè)角色才能訪問(wèn)
*/
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add", "authc");
filterMap.put("/user/update", "authc");
bean.setFilterChainDefinitionMap(filterMap);
//設(shè)置登錄的請(qǐng)求
bean.setLoginUrl("/toLogin");
return bean;
}
//DefaultWebSecurityManager
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//關(guān)聯(lián) UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//創(chuàng)建Realm對(duì)象,需要自定義類(lèi)
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
Shiro實(shí)現(xiàn)用戶認(rèn)證
步驟:
1、在 UserRealm中,編寫(xiě)認(rèn)證方法
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執(zhí)行了shiro的認(rèn)證方法");
//用戶名、密碼(要從數(shù)據(jù)庫(kù)中獲取)
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken)token;
if(!userToken.getUsername().equals(name)){ //如果userToken中的username和數(shù)據(jù)庫(kù)中取出來(lái)的name不一樣
return null; //拋出異常 UnknownAccountException
}
//密碼認(rèn)證,shiro做
return new SimpleAuthenticationInfo("",password,"");
}2、在controller中封裝用戶數(shù)據(jù)
@RequestMapping("/login")
public String login(String username, String password, Model model){
//獲取當(dāng)前用戶
Subject subject = SecurityUtils.getSubject();
//封裝用戶的登錄數(shù)據(jù)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try{
subject.login(token); //執(zhí)行登錄方法,如果沒(méi)有異常說(shuō)明就ok了
return "index";
}catch (UnknownAccountException e){ //用戶名不存在
model.addAttribute("msg","用戶名錯(cuò)誤");
return "login";
}catch (IncorrectCredentialsException e){ //密碼不存在
model.addAttribute("msg","密碼錯(cuò)誤");
return "login";
}
}步驟解析:




Shiro整合MyBatis
步驟:
1、導(dǎo)入依賴(lài)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>2、編寫(xiě)application.yaml和application.properties配置文件
①application.yaml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默認(rèn)是不注入這些屬性值的,需要自己綁定
#druid 數(shù)據(jù)源專(zhuān)有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置監(jiān)控統(tǒng)計(jì)攔截的filters,stat:監(jiān)控統(tǒng)計(jì)、log4j:日志記錄、wall:防御sql注入
#如果允許時(shí)報(bào)錯(cuò) java.lang.ClassNotFoundException: org.apache.log4j.Priority
#則導(dǎo)入 log4j 依賴(lài)即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500②application.properties
mybatis.type-aliases-package=com.pojo mybatis.mapper-locations=classpath:mapper/*.xml
3、編寫(xiě)實(shí)體類(lèi)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private int id;
private String name;
private String pwd;
}
4、編寫(xiě)mapper層
①UserMapper接口
@Repository
@Mapper
public interface UserMapper {
//根據(jù)用戶名查用戶信息
public User queryUserByName(String name);
}
②UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from mybatis.user where name = #{name};
</select>
</mapper>5、編寫(xiě)service層
①UserService接口
public interface UserService{
public User queryUserByName(String name);
}
②UserServiceImpl
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
6、把之前在UserRealm中直接寫(xiě)的name和password,改成從數(shù)據(jù)庫(kù)中查出來(lái)的
public class UserRealm extends AuthorizingRealm {
@Autowired
UserServiceImpl userService;
//授權(quán)
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了shiro的授權(quán)方法");
return null;
}
//認(rèn)證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執(zhí)行了shiro的認(rèn)證方法");
UsernamePasswordToken userToken = (UsernamePasswordToken)token;
//連接真實(shí)的數(shù)據(jù)庫(kù)
User user = userService.queryUserByName(userToken.getUsername());
//如果user為空,說(shuō)明用戶不存在
if(user == null){
return null; //拋異常 UnknownAccountException
}
//密碼認(rèn)證,shiro做
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}Shiro請(qǐng)求授權(quán)實(shí)現(xiàn)
1、在ShiroConfig中設(shè)置訪問(wèn)哪些路徑,需要哪些權(quán)限,并配置未授權(quán)頁(yè)面
filterMap.put("/user/add","perms[user:add]"); //擁有 user:add 權(quán)限才能訪問(wèn)/user/add
filterMap.put("/user/update","perms[user:update]"); bean.setUnauthorizedUrl("/noauth");
2、在UserRealm中給當(dāng)前用戶授權(quán),其中權(quán)限是從數(shù)據(jù)庫(kù)中查出來(lái)的
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執(zhí)行了shiro的授權(quán)方法");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到當(dāng)前登錄的這個(gè)對(duì)象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal(); //拿到user對(duì)象
info.addStringPermission(currentUser.getPerms());
return info;
}
3、在controller中設(shè)置未授權(quán)url處理
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未經(jīng)授權(quán),無(wú)法訪問(wèn)此頁(yè)面";
}Shiro整合Thymeleaf
1、導(dǎo)入依賴(lài)
<!--shiro-thymeleaf整合-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>2、在shiroConfig中整合thymeleaf
//ShiroDialect:用來(lái)整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}3、更改前端頁(yè)面
①在test頁(yè)面編寫(xiě)一個(gè)登錄連接
<p>
<a th:href="@{/toLogin}" rel="external nofollow" >登錄</a>
</p>
②在首頁(yè)設(shè)置add和update鏈接,擁有對(duì)應(yīng)權(quán)限才可以訪問(wèn)
shiro命名空間:
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
鏈接:
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}" rel="external nofollow" rel="external nofollow" >add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}" rel="external nofollow" rel="external nofollow" >update</a>
</div>
到此這篇關(guān)于SpringBoot中的Shiro及環(huán)境搭建的文章就介紹到這了,更多相關(guān)springboot shiro全解析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot基于IDEA環(huán)境熱加載與熱部署教程
這篇文章主要為大家介紹了springboot在IDEA環(huán)境下的熱加載與熱部署教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
SpringBoot搭配AOP實(shí)現(xiàn)自定義注解
這篇文章主要為大家詳細(xì)介紹了SpringBoot如何搭配AOP實(shí)現(xiàn)自定義注解,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2022-12-12
Springboot使用test無(wú)法啟動(dòng)問(wèn)題的解決
這篇文章主要介紹了Springboot使用test無(wú)法啟動(dòng)問(wèn)題的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
解析Spring中的靜態(tài)代理和動(dòng)態(tài)代理
學(xué)習(xí) Spring 的過(guò)程中,不可避免要掌握代理模式。這篇文章總結(jié)一下代理模式。顧名思義,代理,就是你委托別人幫你辦事,所以代理模式也有人稱(chēng)作委托模式的。比如領(lǐng)導(dǎo)要做什么事,可以委托他的秘書(shū)去幫忙做,這時(shí)就可以把秘書(shū)看做領(lǐng)導(dǎo)的代理2021-06-06
SpringCloud Feign傳遞HttpServletRequest對(duì)象流程
HttpServletRequest接口的對(duì)象代表客戶端的請(qǐng)求,當(dāng)客戶端通過(guò)HTTP協(xié)議訪問(wèn)Tomcat服務(wù)器時(shí),HTTP請(qǐng)求中的所有信息都封裝在HttpServletRequest接口的對(duì)象中,這篇文章介紹了Feign傳遞HttpServletRequest對(duì)象的流程,感興趣的同學(xué)可以參考下文2023-05-05

