shiro流程总结:
shiro配置文件
1、将自定义的realm对象注入到容器中(可以对realm设置加密方式MD5 SHA-256)
2、将WebSecurityManager注入容器,将realm对象set到manager中,(也可以设置rememberme功能,将cookieRememberMeManager对象set到manager中
3、将ShiroFilterFactoryBean注入容器,并将WebSecurityManager对象set到ShiroFilterFactoryBean属性中
4、在工厂对象设置工厂属性:
(1)使用map设置页面访问认证和权限,将map对象set到setFilterChainDefinitionMap 方法中
(2)无权访问时跳转的指定页面 bean.setLoginUrl("/toLogin");
(3) 未授权跳转controller请求 bean.setUnauthorizedUrl("/noauth");
自定义的realm
授权过程:
即在授权方法中获取当前登陆人信息,访问数据库查到登陆人的登陆权限或者角色,将权限和角色设置到对应的属性中
认证过程:
获取到封装用户登录名和密码的token,通过用户名拿到用户信息,
返回一个方法方法中传入获取到的用户信息、用户密码、加盐、当前realm对象名,shiro后台帮你验证
controller登陆
1、拿到用户名、密码,将其封装到UsernamePasswordToken对象中
2、获取shiro当前subject,调用subject.login(token)方法,将token参数传入,即可完成用户的认证和授权
Shiro
快速开始Shiro
- 导包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- 配置log4j.properties和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
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
- 编写demo
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);
// 获取当前的用户对象
Subject currentUser = SecurityUtils.getSubject();
// 通过当前用户,拿到session (shiro框架的session不是http的)可以脱离web使用
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 + "]");
}
// 判断当前的用户是否被认证
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?
}
}
//当前用户信息
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.");
}
//粗粒度的权限
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.");
}
//细粒度的权限
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);
}
}
springboot集成shiro
- 导包添加shiro依赖
<!--
Subject 用户
SecurityManager 管理所有用户
Realm 链接数据
-->
<!--shiro整合spring的包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.0</version>
</dependency>
<!--整合mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<!--整合druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--整合thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!--整合thymeleaf - shiro-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 自定义Realm
//自定义的realm
public class UserRealm extends AuthorizingRealm {
@Resource
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到当前登陆对象,
// 在认证过程中一定要将 user 放入 new SimpleAuthenticationInfo(user, user.getPwd(), credentialsSalt,realmName);
Subject subject = SecurityUtils.getSubject();
User currentUser = (User)subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
//设置角色授权
// /**2.2、用户的角色集合 **/
// info.addRoles(user.getRolesName());
// /**2.3、用户的角色对应的所有权限,如果只使用角色定义访问权限,下面的四行可以不要 **/
// List<Role> roleList=user.getRoleList();
// for (Role role : roleList) {
// info.addStringPermissions(role.getPermissionsName());
// }
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证");
//获取 MD5加盐加密hash值
// String hashAlgorithName = "MD5";
// String password = "123456";
// int hashIterations = 1024;//加密次数
// ByteSource credentialsSalt = ByteSource.Util.bytes("王罕");
// Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
// System.out.println(obj);
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
//链接真实数据库
User user = userService.queryByName(token.getUsername());
if(user==null){
return null; //返回空值,默认抛用户名不存在的异常
}
//当前realm对象的name
String realmName = this.getName();
//加盐
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getName());
//密码认证 密码验证时shiro帮你验证的
//第一个参数user 是将user信息由认证传递到授权方法中
return new SimpleAuthenticationInfo(user, user.getPwd(), credentialsSalt,realmName);
}
}
- 编写Shiro配置文件
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFlterFactoryBean(
@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager
){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加Shiro的内置过滤器
/*
* anon:无需认证就可以访问
* authc:必须认证才可以访问
* user:必须拥有记住我功能才能访问
* perms:拥有对某个资源的权限才能访问
* roles:拥有某个角色权限才能访问
* */
//登陆拦截
Map<String, String> filterMap = new LinkedHashMap<>();
//细粒度的拦截控制要放在最前面,否则细粒度拦截会不生效
//角色 多个参数时 role["admin,customer"]
filterMap.put("/user/add","roles[admin]");
//认证之后,还要有权限才可以访问 多个参数 perms["user:add,user:update"]
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
//需要认证才可以访问
filterMap.put("/index","authc");
filterMap.put("/","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//无权访问,设置跳转到登陆页面 controller
bean.setLoginUrl("/toLogin");
//未授权跳转controller请求
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager 第二步 @Qualifier 注解与我们想要使用的特定 Spring bean 的名称一起进行装配
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm
,@Qualifier("rememberManager")CookieRememberMeManager rememberMeManager){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联Realm
securityManager.setRealm(userRealm);
//关联RememberMeManager
securityManager.setRememberMeManager(rememberMeManager);
return securityManager;
}
//创建Realm对象,注入IOC容器 第一步
@Bean
public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher) {
//用户认证在Realm中
UserRealm realm = new UserRealm();
realm.setAuthenticationCachingEnabled(false);
realm.setCredentialsMatcher(matcher);
return realm;
}
//设置shiro MD5加密验证
@Bean("hashedCredentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//加密次数
credentialsMatcher.setHashIterations(1024);
//指定加密方式为MD5 也可以指定 SHA-256 "SHA-256"
credentialsMatcher.setHashAlgorithmName("MD5");
credentialsMatcher.setStoredCredentialsHexEncoded(true);
return credentialsMatcher;
}
//整合ShiroDialect 用来整合shiro-thymeleaf ,这样thymeleaf中就可以使用shiro标签,控制页面的展示了
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
//RememberMe整合
@Bean("rememberManager")
public CookieRememberMeManager cookieRememberMeManager(@Qualifier("rememberMeCookie") SimpleCookie cookie){
CookieRememberMeManager manager = new CookieRememberMeManager();
manager.setCipherKey(Base64.decode("6ZmI6I2j3Y+R1aSn5BOlAA=="));
manager.setCookie(cookie);
return manager;
}
@Bean
public SimpleCookie rememberMeCookie(){
SimpleCookie cookie = new SimpleCookie();
cookie.setHttpOnly(true);
cookie.setMaxAge(7*24*600*60);
//cookie的name不能为空,要设置name
cookie.setName("shiro");
return cookie;
}
- 页面的控制
@Controller
public class MyController {
@RequestMapping({"/index", "/"})
public String index(Model model) {
model.addAttribute("msg", "hello shiro");
return "index";
}
@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";
}
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized() {
return "未经授权,无法访问";
}
@RequestMapping("/login")
public String login(String username, String password, Model model) {
//获取当前用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登陆数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
try {
subject.login(token);//执行登陆方法,如果没有异常就说明OK
User user = (User) subject.getPrincipal();
Session session = subject.getSession();
session.setAttribute("user",user);
} catch (UnknownAccountException e) {
model.addAttribute("msg", "用户名不存在");
return "login";
} catch (IncorrectCredentialsException e) {
model.addAttribute("msg", "密码错误");
return "login";
} catch (LockedAccountException lae) {
model.addAttribute("msg", "用户被锁定");
return "login";
}
return "index";
}
}
- thymeleaf整合shiro,对应有权限的页面才展示
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text = "${msg}"></p>
<hr>
<div th:if="${session.user}==null">
登陆之后不显示
</div>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<hr>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>
MD5加密
String hashAlgorithName = "MD5";
String password = "123456";
int hashIterations = 1024;//加密次数
ByteSource credentialsSalt = ByteSource.Util.bytes("陈蒙");
Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
System.out.println(obj);
SHA-256
String hashAlgorithName = "SHA-256";
String password = "123456";
int hashIterations = 1024;//加密次数
ByteSource credentialsSalt = ByteSource.Util.bytes("陈蒙");
Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
System.out.println(obj);
注:shiro在使用SHA-256加密验证密码的时候容易报错
org.apache.shiro.crypto.CryptoException: Unable to execute 'doFinal' with cipher instance [javax.crypto.Cipher@7c2a9e47].
原因:
项目中使用Shiro作为认证权限控制框架,问题就出在RememberMe功能的配置上,rememberMeManager
继承了AbstractRememberMeManager,然而AbstractRememberMeManager的构造方法中每次都会重
新生成对称加密密钥,意味着每次重启程序都会重新生成一对加解密密钥。这就会导致了,第一次启动程序
shiro使用A密钥加密了cookie,第二次启动程序shiro重新生成了密钥B,当用户访问页面时,shiro会
用密钥B去解密上一次用密钥A加密的cookie,导致解密失败,导致报错,所以这不影响用户登录操作
(rememberMe失效罢了),所以这种异常只会在程序重启(shiro清除session)第一次打开页面的时候出现。
解决办法:手动设置对称加密秘钥。