Shiro
一、快速入门
- 导包
<dependencies>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
- 配置配置文件
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
shiro.ini
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
- Helloworld
完整代码参考博客 https://www.pangtun.com/4819.html
- API
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");//读取配置文件
securityManager.setRealm(iniRealm);//初始化securityManager
SecurityUtils.setSecurityManager(securityManager);//将securityManager注入到工具类
Subject currentUser = SecurityUtils.getSubject();//创建Subject对象
Session session = currentUser.getSession();//通过Subject获取session
currentUser.isAuthenticated();//判断用户是否认证
currentUser.hasRole("schwartz");//判断用户是否拥有某个角色
currentUser.isPermitted("lightsaber:wield");//判断用户是否有某种权限
currentUser.logout();//注销
二、使用shiro-编写配置类
- 编写ShiroConfig类 分别注册ShiroFilterFactoryBean,DefaultWebSecurityManager,UserRealm三个类
package com.liao.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean =new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return shiroFilterFactoryBean;
}
//DefaultWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm对象
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象 自定义
@Bean(name = "userRealm")
public UserRealm getUserRealm(){
return new UserRealm();
}
}
2.添加权限认证
shiro内置的过滤器用于拦截请求
- anon:无需认证就能访问
- authc:必须认证了才能访问
- user:必须拥有 记住我 功能才能访问
- perms:必须拥有某个资源的权限才能访问
- role:必须拥有某个角色权限才能访问
在shiro的配置类中添加内置的过滤器authc,拦截请求为"/user/add"和"/user/update",这样,当用户没有认证去访问这两个请求时会跳转到认证界面(登录界面)
Map<String, String> filterMap = new LinkedHashMap<>();//用于封装拦截的请求
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
shiroFilterFactoryBean.setLoginUrl("/toLogin");//设置跳转的认证界面
认证方式
表单提交到控制器,接收用户名和密码后,封装成令牌,调用subject.login(token)到后台进行验证,令牌会封装到UsernamePasswordToken,在UserRealm中进行验证用户名和密码
controller
@RequestMapping("/login")
public String login(String username,String password,Model model){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try{
subject.login(token);
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
UserRealm
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("进行了=>认证 doGetAuthorizationInfo");
//用户名密码验证
String username = "root";
String password = "will";
UsernamePasswordToken token1 = (UsernamePasswordToken)token;
//验证用户名
if (!token1.getUsername().equals(username)){
return null;
}
//验证密码
return new SimpleAuthenticationInfo("",password,"");
}
三、整合mybatis
导包
<!--整合mybatis-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</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.1.3</version>
</dependency>
四、授权
在数据库中增加字段,用于记录用户权限,当进行认证时,将查询到的用户,封装成principal对象并且通过SimpleAuthenticationInfo(user,token1.getPassword(),"");方法封装到Subject中,用户通过获取Subject,进而获取到权限信息,并授予用户,最后返回授权info对象
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("进行了=>授权 doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
info.addStringPermission(currentUser.getPerms());
return info;
}
五、整合thymeleaf
- 导包
<!--整合thymleaf和shiro-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
- 配置bean(在ShiroConfig中)
//整合ShiroDialect
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
- 前端页面引入命名空间
xmlns:shiro="http://www.thymleaf.org/thymeleaf-extras-shiro
- 使用方法
可以通过session进行前后端传值,
后端存值代码
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("user",user);
前端取值代码
<div th:if="${session.user==null}">//若用户登录了,就隐藏标签
<a th:href="@{/toLogin}" >去登录</a>
</div>
<div shiro:hasPermission="user:add">//当用户有user:add权限时,才显示
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>