shiro的授权与认证
shiro的授权与认证
package com.cy.pj.common.aspect;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.common.util.IPUtils;
import com.cy.pj.sys.dao.SysLogDao;
import com.cy.pj.sys.entity.SysLog;
import com.cy.pj.sys.entity.SysUser;
/**
* @Aspect 注解修饰的类通常认为一个切面对象类型
* 切面对象是对扩展业务的封装,它通常会在内部声明
* 如下几个部分.
* 1)实现扩展业务的方法(一般会称为通知-advice)
* 2)切入扩展业务的点(一般会称为切入点-PointCut)
*/
//@Order(1)
@Aspect
@Service
public class SysLogAspect {//日志切面
/**
* @Around注解修饰方法为一个环绕通知,其目的
* 是在目标业务方法执行之前和之后都可以进行
* 扩展业务的处理
* 其中:
* 1)bean(sysUserServiceImpl) 为切入点表达式,
* 表示sysUserServiceImpl对象中所有业务方法执行
* 时都会执行@Around注解修饰的方法
* @param jp 连接点(封装了要执行的目标方法信息)
* @return
* @throws Throwable
*/
//@Around("bean(sysUserServiceImpl)")
//@Around("bean(*ServiceImpl)")
//@annotation()为细粒度的切入点表达式定义方式
@Around("@annotation(com.cy.pj.common.annotation.RequiredLog)")
public Object aroundMethod(ProceedingJoinPoint jp)
throws Throwable{
System.out.println("LogAspect:开始记录日志");
//1.目标业务执行之前的记录
long t1=System.currentTimeMillis();
//2.执行目标业务(底层通过反射执行目标方法)
Object result=jp.proceed();
//3.目标业务执行之后的记录
long t2=System.currentTimeMillis();
System.out.println("目标业务执行时长:"+(t2-t1));
saveObject(jp,(t2-t1));
//4.返回目标业务的执行结果
return result;
}
@Autowired
private SysLogDao sysLogDao;
private void saveObject(ProceedingJoinPoint jp,long time)throws Exception {
//1.获取要保存的日志信息
//1.1获取登陆用户(没问题)
SysUser user=(SysUser)SecurityUtils.getSubject().getPrincipal();
//1.2获取方法签名(此对象封装了我们要执行的目标方法信息)
Signature s=jp.getSignature();
System.out.println(s.getClass().getName());//MethodSignature
MethodSignature ms=(MethodSignature)s;
//1.2.1获取目标对象(要执行的业务层对象)
Class<?> targetClass=jp.getTarget().getClass();
//1.2.2基于目标业务对象获取要执行的目标方法
//?思考(为什么要获取此方法呢)
Method targetMethod=targetClass.getDeclaredMethod(
ms.getName(),
ms.getParameterTypes());
//1.2.3获取方法上定义的注解内容(定义的操作名)
RequiredLog requiredLog=
targetMethod.getDeclaredAnnotation(RequiredLog.class);
String operation=requiredLog.value();
//1.2.4获取目标对象方法的全称(类全名+方法名)
String targetClassName=targetClass.getName();
String targetMethodName=targetClassName+"."+targetMethod.getName();
//1.3获取方法执行时的实际参数
String params=Arrays.toString(jp.getArgs());
//2.封装日志信息
SysLog log=new SysLog();
log.setUsername(user.getUsername());
log.setIp(IPUtils.getIpAddr());
log.setOperation(operation);
log.setMethod(targetMethodName);
log.setParams(params);
log.setTime(time);
log.setCreatedTime(new Date());
//3.将日志信息写入到数据库
sysLogDao.insertObject(log);
}
}
shiro的配置
package com.cy.pj.common.config;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import com.cy.pj.sys.service.realm.ShiroUserRealm;
/** Shiro的配置文件 */
@Configuration
public class SpringShiroConfig {
/**单机环境,session交给shiro管理*/
@Bean
public DefaultWebSessionManager newSessionManager(){
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionValidationSchedulerEnabled(true);
sessionManager.setSessionIdUrlRewritingEnabled(false);
sessionManager.setSessionValidationInterval(3600 * 1000);
sessionManager.setGlobalSessionTimeout(3600 * 1000);
return sessionManager;
}
@Bean("securityManager")
public SecurityManager newSecurityManager(ShiroUserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
securityManager.setSessionManager(newSessionManager());
securityManager.setRememberMeManager(newRememberMeManager());
securityManager.setCacheManager(newCacheManager());
return securityManager;
}
public RememberMeManager newRememberMeManager() {
CookieRememberMeManager cManager=new CookieRememberMeManager();
cManager.setCookie(newCookie());
return cManager;
}
public SimpleCookie newCookie() {
SimpleCookie sc=new SimpleCookie("simpleCookie");
sc.setMaxAge(7*24*60*60);
return sc;
}
public CacheManager newCacheManager() {
MemoryConstrainedCacheManager cacheManager=new MemoryConstrainedCacheManager();
return cacheManager;
}
@Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
shiroFilter.setLoginUrl("/doLoginUI");
shiroFilter.setUnauthorizedUrl("/");
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/bower_components/**", "anon");
filterMap.put("/build/**", "anon");
filterMap.put("/dist/**", "anon");
filterMap.put("/plugins/**", "anon");
filterMap.put("/user/doLogin","anon");
filterMap.put("/doLogout", "logout");
filterMap.put("/**", "authc");
shiroFilter.setFilterChainDefinitionMap(filterMap);
return shiroFilter;
}
@Bean("lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
@DependsOn("lifecycleBeanPostProcessor")
public DefaultAdvisorAutoProxyCreator newProxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
拦截
package com.cy.pj.common.config;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
@Configuration
public class WebFilterConfig {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Bean
public FilterRegistrationBean shiroFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
//该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
//registration.addInitParameter("targetFilterLifecycle", "true");
registration.setEnabled(true);
registration.setOrder(Integer.MAX_VALUE - 1);
registration.addUrlPatterns("/*");
return registration;
}
}
shiro的授权与认证的更多相关文章
- shiro 身份授权+权限认证
https://www.cnblogs.com/cmyxn/p/5825099.html
- Shiro+Mybatis实现登录认证、授权功能
Shiro+Mybatis实现登录认证.授权功能 一.实现登录认证功能 1.流程: 跟据用户提交表单的账号,经Mybatis框架在数据库中查出User对象: 如果User为空,则会抛出异常:Unkno ...
- 【SpringBoot技术专题】「权限校验专区」Shiro整合JWT授权和认证实现
本章介绍一下常用的认证框架Shiro结合springboot以及集合jwt快速带您开发完成一个认证框架机制. Maven配置依赖 <dependency> <groupId>o ...
- Shiro【授权、整合Spirng、Shiro过滤器】
前言 本文主要讲解的知识点有以下: Shiro授权的方式简单介绍 与Spring整合 初始Shiro过滤器 一.Shiro授权 上一篇我们已经讲解了Shiro的认证相关的知识了,现在我们来弄Shiro ...
- Shiro【授权过滤器、与ehcache整合、验证码、记住我】
前言 本文主要讲解的知识点有以下: Shiro授权过滤器使用 Shiro缓存 与Ehcache整合 Shiro应用->实现验证码功能 记住我功能 一.授权过滤器测试 我们的授权过滤器使用的是pe ...
- 【Shiro】Apache Shiro架构之权限认证(Authorization)
Shiro系列文章: [Shiro]Apache Shiro架构之身份认证(Authentication) [Shiro]Apache Shiro架构之集成web [Shiro]Apache Shir ...
- 【Shiro】Apache Shiro架构之身份认证(Authentication)
Shiro系列文章: [Shiro]Apache Shiro架构之权限认证(Authorization) [Shiro]Apache Shiro架构之集成web [Shiro]Apache Shiro ...
- Shrio00 Shiro角色授权、Shiro权限授权、开启Shiro缓存
1 需求01 用户进行过认证登录后,某些接口是有权限限制的:如何实现只有相应权限的用户才可以调用相应接口 2 修改shiro配置类 ShiroConfiguration package cn.xia ...
- Shiro:授权的相关实现
Shiro:授权的相关实现 一.使用Shiro过滤器实现授权 设置好授权拦截跳转的请求地址 /** * 创建ShiroFilterFactoryBean */ @Bean public ShiroFi ...
随机推荐
- [LeetCode]547. Friend Circles朋友圈数量--不相邻子图问题
/* 思路就是遍历所有人,对于每一个人,寻找他的好友,找到好友后再找这个好友的好友 ,这样深度优先遍历下去,设置一个flag记录是否已经遍历了这个人. 其实dfs真正有用的是flag这个变量,因为如果 ...
- JTable写入数据库内容
/*JTable中导入数据库数据. 创建2个Vector col和dat col存入字段名 dat存入数据内容. dbname=new JTable(dat,col); */package demo; ...
- redis加锁的几种实现
redis加锁的几种实现 2017/09/21 1. redis加锁分类 redis能用的的加锁命令分表是INCR.SETNX.SET 2. 第一种锁命令INCR 这种加锁的思路是, key 不存在, ...
- Failed to create Spark client for Spark session
最近在hive里将mr换成spark引擎后,执行插入和一些复杂的hql会触发下面的异常: org.apache.hive.service.cli.HiveSQLException: Error whi ...
- linux下 shell时间处理
一.hour #获取当前时间年月日时分秒current_create_time=`date +"%Y-%m-%d %H:%M:%S"` echo $current_create_t ...
- idea破解方式:永久激活
相信很多小伙伴都发现了,每年到年底的时候,idea注册码都大面积的失效,早上到办公室打开电脑发现注册码过期,还要花很长时间找新的: 这里介绍两种破解方式,都是有生之年不到期:与网上现有的方式基本一致. ...
- Python解释器和IPython
目录 简介 Python解释器 IPython 魔法函数 运行和编辑 Debug History 运行系统命令 简介 今天给大家介绍一下Python的一个功能非常强大的解释器IPython.虽然Pyt ...
- TeamView WaitforConnectFailed错误原因
更新到最新版本并重启如下服务 检查TCP IPV4是否选中
- 多媒体开发(5)&音频特征:声音可以调大一点吗?
基本上,现在常用的声音采样办法是pcm,而对于压缩音频的解码,得到的也pcm数据.这个pcm数据,只是一堆数值,有正有负,看这个值看不出什么花样. 声音采集,采的是什么呢? 采的是声音的强度变化,也是 ...
- ACL技术(访问控制列表)
• Access Control List • 访问控制列表 • 是一种包过滤技术 • ACL基于IP包头的IP地址.四层TCP/UDP头部的端口号.[五层数据]进行过滤 • ...