什么是Shiro?
shiro官网:https://shiro.apache.org/
Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。
使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。
Shiro功能?
第一步:导入相关依赖
<dependencies>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
<version>1.5.3version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>jcl-over-slf4jartifactId>
<version>1.7.30version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.30version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
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
[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:eagle5
第四步:引入quickStart
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
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;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// 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);
}
}
第五步:运行quickStart测试 (下面是测试结果)
2020-07-25 13:42:47,366 INFO [Quickstart] - Retrieved the correct value! [aValue]
2020-07-25 13:42:47,368 INFO [Quickstart] - User [lonestarr] logged in successfully.
2020-07-25 13:42:47,368 INFO [Quickstart] - May the Schwartz be with you!
2020-07-25 13:42:47,368 INFO [Quickstart] - You may use a lightsaber ring. Use it wisely.
2020-07-25 13:42:47,369 INFO [Quickstart] - You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. Here are the keys - have fun!
基于以上官网快速入门案例就搭建完成了 现在就是我们研究shiro到底如何使用的时候了
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
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;
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
/**
* 这段话主要是我们可以通过读取shiro.ini中的内容(user是用户,role是角色)得到一个工厂对象来实例化SecurityManager
* 管理shiro内部组件提供安全管理的各种服务,并通过SecurityUtils工具类将securityManager
* 设置进去
*
* shiro.ini文件配置了用户权限以及认证
*/
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
//拿到当前用户对象
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户拿到Shiro的Session对象
Session session = currentUser.getSession();
//通过Session进行存值取值 并将值强转为String类型
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("拿到的Subject对象的Session中value为 [" + value + "]");
}
//判断当前用户对象是否已经认证
if (!currentUser.isAuthenticated()) {
//根据你的账号密码生成一个令牌(token) 这是与shiro.ini文件相对应的 也就是说可以自己改ini文件进行设置
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
//token令牌设置记住我
token.setRememberMe(true);
//下面三个登录异常分别是没有当前对象、密码错误、账户被锁定
try {
currentUser.login(token);
} catch (UnknownAccountException uae) {
log.info("没有当前用户对象 " + 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 (AuthenticationException ae) {
//unexpected condition? error?
}
}
//打印当前用户对象
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//判断用户角色
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//用户是否被允许有这样的实力级权限(这个权限是属于schwartz用户角色的)
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.");
}
//判断是否拥有实例级权限(这个权限是属于goodguy用户角色的)
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!");
}
//用户注销
currentUser.logout();
System.exit(0);
}
}
Subject currentUser = SecurityUtils.getSubject();//拿到当前用户对象
Session session = currentUser.getSession(); //通过当前用户拿到Shiro的Session对象
UsernamePasswordToken token = new UsernamePasswordToken("账号", "密码");//根据你的账号密码生成一个令牌(token)
token.getPrincipal();//获取当前用户对象
currentUser.isAuthenticated()//判断当前用户对象是否已经认证
currentUser.hasRole("schwartz")//判断用户角色
currentUser.isPermitted("lightsaber:wield")//用户是否被允许有这样的实力级权限
currentUser.logout();//用户注销
首先这个web项目是需要我们连接数据库的,所以需要一下信息
数据库信息(数据库驱动mysql-driver、数据库连接池Druid、数据库依赖mysql)
SpringBoot-web场景启动器
Mybatis场景启动器
Shiro场景启动器
thymeleaf场景启动器
Shiro整合Thymeleaf
log4j日志
第一步:导入相关依赖
<dependencies>
<dependency>
<groupId>com.github.theborakompanionigroupId>
<artifactId>thymeleaf-extras-shiroartifactId>
<version>2.0.0version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.20version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.22version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.3version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-spring-boot-starterartifactId>
<version>1.5.3version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
第二步:编写Shiro配置
三个核心对象对应相应的方法或类来创建
Subject当前用户对应:ShiroFilterFactoryBean
SecurityManager对应:DefaultWebSecurityManager
Realm对象对应继承AuthorizingRealm而创建
这三个对象的创建方式应该由下往上,因为上面一个会调用下面一个,需要通过@Qualifier指定@Bean的值
首先编写UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
}
}
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
return factoryBean;
}
@Bean("defaultWebSecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
@Bean("userRealm")
public UserRealm userRealm() {
return new UserRealm();
}
}
<h1 >首页h1>
<h1 th:href="@{/toLogin}">h1>
<hr>
<a th:href="@{/user/add}">adda><br>
<a th:href="@{/user/update}">updatea>
@RequestMapping("/user/add")
public String toAdd(){
return "user/add";
}
@RequestMapping("/user/update")
public String toUpdate(){
return "user/update";
}
<h1>addh1>
<h1>updateh1>
第三步:shiro实现登录拦截
<form th:action="@{/login}">
<p>用户名:<input type="text" name="username">p>
<p>密 码:<input type="password" name="password">p>
<input type="submit" value="提交">
form>
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
//设置登录页面
factoryBean.setLoginUrl("/toLogin");
第四步:shiro实现用户认证
@RequestMapping("/login")
public String login(String username,
String password,
Model model){
//获取当前用户
Subject currentUser = SecurityUtils.getSubject();
//封装用户数据
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
try {
currentUser.login(token);
return "index";
} catch (UnknownAccountException uae) {
model.addAttribute("errormsg","用户名错误!");
return "login";
} catch (IncorrectCredentialsException ice) {
model.addAttribute("errormsg","密码错误!");
return "login";
}
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证doGetAuthenticationInfo方法!");
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//将参数token强转为我们需要的UsernamePasswordToken
User user= userService.findByUsername(token.getUsername());
if (user==null){
return null;
}
//SimpleAuthenticationInfo是AuthenticationInfo的子类 返回时需要注意三个参数,一个是User对象通过username获取的
//一个是password密码数据库获得,最后的是realmName
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
<div th:text="${errormsg}" style="color: red">div>
第五步:shiro授权功能实现
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
factoryBean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
anno 无需认证就可以访问
authc 必须认证才能访问
user 必须拥有记住我功能才能用
perms 拥有对某个资源权限才能访问
role 拥有某个角色权限才能访问
*/
Map<String, String> map = new LinkedHashMap<String, String>();
//设置授权
map.put("/user/add","perms[user:add]");
map.put("/user/update","perms[user:update]");
map.put("/user/*", "authc");
factoryBean.setFilterChainDefinitionMap(map);
factoryBean.setUnauthorizedUrl("/unauthorized");
//设置登录页面
factoryBean.setLoginUrl("/toLogin");
return factoryBean;
}
//授权
@ResponseBody
@RequestMapping("/unauthorized")
public String unauthorized(){
return "未授权!请联系管理员!";
}
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了doGetAuthorizationInfo授权方法!");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");
//拿到当前对象
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
info.addStringPermission(user.getPerms());
return info;
}
第六步:Shiro集成Thymeleaf
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h1 th:text="${msg}">首页h1>
<h1 th:href="@{/toLogin}">h1>
<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">adda><br>
div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">updatea>
div>
body>
html>