Shiro

  Shiro 主要分为 安全认证 和 接口授权 两个部分,其中的核心组件为 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已经为我们封装好了,我们只需要按照一定的规则去编写响应的代码即可…

  Subject 表示主体,将用户的概念理解为当前操作的主体,它即可以是一个通过浏览器请求的用户,也可能是一个运行的程序,外部应用与 Subject 进行交互,记录当前操作用户。Subject 代表当前用户的安全操作,SecurityManager 则管理所有用户的安全操作。

  SecurityManager 即安全管理器,对所有的 Subject 进行安全管理,并通过它来提供安全管理的各种服务(认证、授权等)

  Realm 充当了应用与数据安全间的 桥梁 或 连接器。当对用户执行认证(登录)和授权(访问控制)验证时,Shiro 会从应用配置的 Realm 中查找用户及其权限信息。

1.导入shiro依赖

        <dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
    
     <!-- hiro-redis插件用于实现:将用户信息交给redis管理 -->
        <dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>2.8.24</version>
</dependency>

2.shiro配置类

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import java.util.LinkedHashMap;
import java.util.Map; @Configuration
public class ShiroConfig { @Value("${spring.redis.shiro.host}")
private String host;
@Value("${spring.redis.shiro.port}")
private int port;
@Value("${spring.redis.shiro.timeout}")
private int timeout;
@Value("${spring.redis.shiro.password}")
private String password; @Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
// 注意过滤器配置顺序 不能颠倒
// 配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了,登出后跳转配置的loginUrl
filterChainDefinitionMap.put("/logout", "logout");
// 配置不会被拦截的链接 顺序判断,在 ShiroConfiguration 中的 shiroFilter 处配置了 /ajaxLogin=anon,意味着可以不需要认证也可以访问
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/*.html", "anon");
filterChainDefinitionMap.put("/ajaxLogin", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/**", "authc");
// 配置shiro默认登录界面地址,前后端分离中登录界面跳转应由前端路由控制,后台仅返回json数据
shiroFilterFactoryBean.setLoginUrl("/unauth");
// 登录成功后要跳转的链接
     // shiroFilterFactoryBean.setSuccessUrl("/index");
// 未授权界面;
     // shiroFilterFactoryBean.setUnauthorizedUrl("/403");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
} /**
* 凭证匹配器
* (由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了)
*
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
hashedCredentialsMatcher.setHashIterations(1024);//散列的次数,比如散列两次,相当于 md5(md5(""));
return hashedCredentialsMatcher;
} @Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
return myShiroRealm;
} @Bean
public SecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(myShiroRealm());
// 自定义session管理 使用redis
securityManager.setSessionManager(sessionManager());
// 自定义缓存实现 使用redis
securityManager.setCacheManager(cacheManager());
return securityManager;
} //自定义sessionManager
@Bean
public SessionManager sessionManager() {
MySessionManager mySessionManager = new MySessionManager();
mySessionManager.setSessionDAO(redisSessionDAO());
return mySessionManager;
} /**
* 配置shiro redisManager
*
* 使用的是shiro-redis开源插件
*
* @return
*/
public RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
redisManager.setHost(host);
redisManager.setPort(port);
redisManager.setExpire(1800);// 配置缓存过期时间
redisManager.setTimeout(timeout);
redisManager.setPassword(password);
return redisManager;
} /**
* cacheManager 缓存 redis实现
*
* 使用的是shiro-redis开源插件
*
* @return
*/
@Bean
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
} /**
* RedisSessionDAO shiro sessionDao层的实现 通过redis
*
* 使用的是shiro-redis开源插件
*/
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
} /**
* 开启shiro aop注解支持.
* 使用代理方式;所以需要开启代码支持;
*
* @param securityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
} /**
* 注册全局异常处理
* @return
*/
@Bean(name = "exceptionHandler")
public HandlerExceptionResolver handlerExceptionResolver() {
return new MyExceptionHandler();
} //自动创建代理,没有这个鉴权可能会出错
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
autoProxyCreator.setProxyTargetClass(true);
return autoProxyCreator;
}
}

3.安全认证和权限验证的核心,自定义Realm

import com.google.gson.JsonObject;
import com.test.cbd.service.UserService;
import com.test.cbd.vo.SysPermission;
import com.test.cbd.vo.SysRole;
import com.test.cbd.vo.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import springfox.documentation.spring.web.json.Json; import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set; public class MyShiroRealm extends AuthorizingRealm {
@Resource
private UserService userInfoService; @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
// // 权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
Session session = SecurityUtils.getSubject().getSession();
UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
// 用户的角色集合
Set<String> roles = new HashSet<>();
roles.add(user.getRoleList().get(0).getRole());
authorizationInfo.setRoles(roles);
return authorizationInfo;
} /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
     // System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
// 获取用户的输入的账号.
String username = (String) token.getPrincipal();
     // System.out.println(token.getCredentials());
// 通过username从数据库中查找 User对象,如果找到,没找到.
// 实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
UserInfo userInfo = userInfoService.findByUsername(username);
// Subject subject = SecurityUtils.getSubject();
// Session session = subject.getSession();
// session.setAttribute("role",userInfo.getRoleList());
// System.out.println("----->>userInfo="+userInfo);
if (userInfo == null) {
return null;
}
if (userInfo.getState() == 1) { //账户冻结
throw new LockedAccountException();
}
String credentials = userInfo.getPassword();
System.out.println("credentials="+credentials);
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
userInfo.getUserName(), //用户名
credentials, //密码
credentialsSalt,
getName() //realm name
);
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("USER_SESSION", userInfo);
return authenticationInfo;
} }

4.全局异常处理器

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map; /**
* Created by Administrator on 2017/12/11.
* 全局异常处理
*/
public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse, Object o, Exception ex) {
ModelAndView mv = new ModelAndView();
FastJsonJsonView view = new FastJsonJsonView();
Map<String, Object> attributes = new HashMap<String, Object>();
if (ex instanceof UnauthenticatedException) {
attributes.put("code", "1000001");
attributes.put("msg", "token错误");
} else if (ex instanceof UnauthorizedException) {
attributes.put("code", "1000002");
attributes.put("msg", "用户无权限");
} else {
attributes.put("code", "1000003");
attributes.put("msg", ex.getMessage());
} view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}
}

5.因为现在的项目大多都是前后端分离的,所以我们需要实现自己的session管理

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable; public class MySessionManager extends DefaultWebSessionManager { private static final String TOKEN = "token"; private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; public MySessionManager() {
super();
} @Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
String id = WebUtils.toHttp(request).getHeader(TOKEN);
//如果请求头中有 token 则其值为sessionId
if (!StringUtils.isEmpty(id)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
return id;
} else {
//否则按默认规则从cookie取sessionId
return super.getSessionId(request, response);
}
}
}

6.控制器

import com.alibaba.fastjson.JSONObject;
import com.test.cbd.vo.UserInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress; @Slf4j
@Api(value="shiro测试",description="shiro测试")
@RestController
@RequestMapping("/")
public class ShiroLoginController { /**
* 登录测试
* @param userInfo
* @return
*/
@RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST)
@ResponseBody
public String ajaxLogin(UserInfo userInfo) {
JSONObject jsonObject = new JSONObject();
UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
jsonObject.put("token", subject.getSession().getId());
jsonObject.put("msg", "登录成功");
} catch (IncorrectCredentialsException e) {
jsonObject.put("msg", "密码错误");
} catch (LockedAccountException e) {
jsonObject.put("msg", "登录失败,该用户已被冻结");
} catch (AuthenticationException e) {
jsonObject.put("msg", "该用户不存在");
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject.toString();
} /**
* 鉴权测试
* @param userInfo
* @return
*/
@RequestMapping(value = "/check", method = RequestMethod.GET)
@ResponseBody
@RequiresRoles("guest")
public String check() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "鉴权测试");
return jsonObject.toString();
}
}

常用注解
@RequiresGuest 代表无需认证即可访问,同理的就是 /path=anon

@RequiresAuthentication 需要认证,只要登录成功后就允许你操作

@RequiresPermissions 需要特定的权限,没有则抛出 AuthorizationException

@RequiresRoles 需要特定的橘色,没有则抛出 AuthorizationException

7.以上就是shiro登陆和鉴权的主要配置和类,下面补充一下其他信息。

①application.properties中shiro-redis相关配置:

spring.redis.shiro.host=127.0.0.1
spring.redis.shiro.port=6379
spring.redis.shiro.timeout=5000
spring.redis.shiro.password=123456

②因为数据是模拟的,所以在登陆认证的时候,并没有通过数据库查用户信息,可以通过以下方式模拟加密后的密码:

    /**
* 生成测试用的md5加密的密码
* @param args
*/
public static void main(String[] args) {
String hashAlgorithmName = "md5";
String credentials = "123456";//密码
int hashIterations = 1024;
ByteSource credentialsSalt = ByteSource.Util.bytes("root");//账号
String obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
System.out.println(obj);
}

上面obj的结果是b1ba853525d0f30afe59d2d005aad96c

③登陆认证的findByUsername方法,模拟到数据库查询用户信息,实际是自己构造的数据,偷偷懒。

    public UserInfo findByUsername(String userName){
SysRole admin = SysRole.builder().role("admin").build();
List<SysPermission> list=new ArrayList<SysPermission>();
SysPermission sysPermission=new SysPermission("read");
SysPermission sysPermission1=new SysPermission("write");
list.add(sysPermission);
list.add(sysPermission1);
admin.setPermissions(list);
UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build();
List<SysRole> roleList=new ArrayList<SysRole>();
roleList.add(admin);
root.setRoleList(roleList);
return root;
}

8.结果演示

输入正确的账号密码时,返回信息如下:

故意输错密码时,返回信息如下:

鉴权时,如果该用户没有角色:

SpringBoot整合Shiro自定义Redis存储的更多相关文章

  1. SpringBoot整合Shiro完成验证码校验

    SpringBoot整合Shiro完成验证码校验 上一篇:SpringBoot整合Shiro使用Redis作为缓存 首先编写生成验证码的工具类 package club.qy.datao.utils; ...

  2. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理|前后端分离(下)----筑基后期

    写在前面 在上一篇文章<SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期>当中,我们初步实现了SpringBoot整合Shiro ...

  3. SpringBoot整合Shiro+MD5+Salt+Redis实现认证和动态权限管理(上)----筑基中期

    写在前面 通过前几篇文章的学习,我们从大体上了解了shiro关于认证和授权方面的应用.在接下来的文章当中,我将通过一个demo,带领大家搭建一个SpringBoot整合Shiro的一个项目开发脚手架, ...

  4. 补习系列(6)- springboot 整合 shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

  5. SpringBoot 整合Shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

  6. SpringBoot整合Shiro权限框架实战

    什么是ACL和RBAC ACL Access Control list:访问控制列表 优点:简单易用,开发便捷 缺点:用户和权限直接挂钩,导致在授予时的复杂性,比较分散,不便于管理 例子:常见的文件系 ...

  7. SpringBoot整合Shiro实现权限控制

    目录 1.SpringBoot整合Shiro 1.1.shiro简介 1.2.代码的具体实现 1.2.1.Maven的配置 1.2.2.整合需要实现的类 1.2.3.项目结构 1.2.4.ShiroC ...

  8. SpringBoot系列十二:SpringBoot整合 Shiro

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 整合 Shiro 2.具体内容 Shiro 是现在最为流行的权限认证开发框架,与它起名的只有最初 ...

  9. SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建

    SpringBoot整合Shiro实现基于角色的权限访问控制(RBAC)系统简单设计从零搭建 技术栈 : SpringBoot + shiro + jpa + freemark ,因为篇幅原因,这里只 ...

随机推荐

  1. 重学c#系列——c#运行原理(二)

    前言 c# 是怎么运行的呢?是否和java一样运行在像jvm的虚拟机上呢?其实差不多,但是更广泛. c# 运行环境不仅c#可以运行,符合.net framework 开发规范的都可以运行. c# 程序 ...

  2. java大数据最全课程学习笔记(2)--Hadoop完全分布式运行模式

    目前CSDN,博客园,简书同步发表中,更多精彩欢迎访问我的gitee pages 目录 Hadoop完全分布式运行模式 步骤分析: 编写集群分发脚本xsync 集群配置 集群部署规划 配置集群 集群单 ...

  3. 什么是控制反转(IoC)?什么是依赖注入(DI)?以及实现原理

    ​ IoC不是一种技术,只是一种思想,一个重要的面向对象编程的法则,它能指导我们如何设计出松耦合.更优良的程序.传统应用程序都是由我们在类内部主动创建依赖对象,从而导致类与类之间高耦合,难于测试:有了 ...

  4. p40_数据交换方式

    一.为什么要数据交换 数据链路发展史: 二.数据交换方式 电路交换 报文交换 分组交换[数据报方式,虚电路方式] 三.电路交换 eg:电话网络(特点:**独占资源,**即使两个人不说话,链接也不会被别 ...

  5. WebView in ScrollView:View not displayed because it is too large to fit into a software layer

    报错信息 W/View: WebView not displayed because it is too large to fit into a software layer (or drawing ...

  6. Mybatis——Mapper解析

    Mapper的注册入口在Configuration的addMapper方法中,其会调用MapperRegistry的addMapper方法. Mapper的注册过程分为两个步骤: 1.创建Mapper ...

  7. vue学习 `${HH}-${mm}-${dd}` 按键修饰符

    vue 有一种拼接字符串的规范写法 //键盘 Tab 键 上边的键 英文输入状态 然后采用类似EL表达式${变量}return `${}:${}:${}` //有时候我们经常在输入完密码之后,按回车E ...

  8. springcloud之简介

    springcloud官方文档翻译网站:https://springcloud.cc/ 一.网站架构的演变过程.(这些架构描述的不是很到位,之后需要从新学习) 传统架构 —> 分布式架构 —&g ...

  9. C#中子类对基类方法的继承、重写和隐藏

    提起子类.基类和方法继承这些概念,肯定大家都非常熟悉.毕竟,作为一门支持OOP的语言,掌握子类.基类是学习C#的基础.不过,这些概念虽然简单,但是也有一些初学者可能会遇到的坑,我们一起看看吧.   子 ...

  10. .NET Core 微服务—API网关(Ocelot) 教程 [二]

    上篇文章(.NET Core 微服务—API网关(Ocelot) 教程 [一])介绍了Ocelot 的相关介绍. 接下来就一起来看如何使用,让它运行起来. 环境准备 为了验证Ocelot 网关效果,我 ...