本文将通过aop的方式实现一个相对更加简易灵活的api安全认证服务。
我们先看实现,然后介绍和分析aop基本原理和常用术语。
一、authorized实现
1、定义注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.power.demo测试数据mon;
import java.lang.annotation.*;
/* * 安全认证 * */ @target ({elementtype.type, elementtype.method}) @retention (retentionpolicy.runtime) @documented public @interface authorized {
string value() default "" ;
} |
这个注解看上去什么都没有,仅仅是一个占位符,用于标志是否需要安全认证。
2、表现层使用注解
1 2 3 4 5 6 7 8 9 10 11 12 |
@authorized @requestmapping (value = "/getinfobyid" , method = requestmethod.post) @apioperation ( "根据商品id查询商品信息" ) @apiimplicitparams ({ @apiimplicitparam (paramtype = "header" , name = "authtoken" , required = true , value = "authtoken" , datatype = "string" ), }) public getgoodsbygoodsidresponse getgoodsbygoodsid( @requestheader string authtoken, @requestbody getgoodsbygoodsidrequest request) {
return _goodsapiservice.getgoodsbygoodsid(request);
} |
看上去就是在一个方法上加了authorized注解,其实它也可以作用于类上,也可以类和方法混合使用。
3、请求认证切面
下面的代码是实现灵活的安全认证的关键:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
package com.power.demo.controller.tool;
import com.power.demo测试数据mon.appconst; import com.power.demo测试数据mon.authorized; import com.power.demo测试数据mon.bizresult; import com.power.demo.service.contract.authtokenservice; import com.power.demo.util.powerlogger; import com.power.demo.util.serializeutil; import org.aspectj.lang.joinpoint; import org.aspectj.lang.annotation.aspect; import org.aspectj.lang.annotation.before; import org.aspectj.lang.annotation.pointcut; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype测试数据ponent; import org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes;
import javax.servlet.http.httpservletrequest; import java.lang.annotation.annotation;
/** * 请求认证切面,验证自定义请求header的authtoken是否合法 **/ @aspect @component public class authorizedaspect {
@autowired private authtokenservice authtokenservice;
@pointcut ( "@annotation(org.springframework.web.bind.annotation.requestmapping)" ) public void requestmapping() { }
@pointcut ( "execution(* com.power.demo.controller.*controller.*(..))" ) public void methodpointcut() { }
/** * 某个方法执行前进行请求合法性认证 注入authorized注解 (先) */ @before ( "requestmapping() && methodpointcut()&&@annotation(authorized)" ) public void dobefore(joinpoint joinpoint, authorized authorized) throws exception {
powerlogger.info( "方法认证开始..." );
class type = joinpoint.getsignature().getdeclaringtype();
annotation[] annotations = type.getannotationsbytype(authorized. class );
if (annotations != null && annotations.length > 0 ) { powerlogger.info( "直接类认证" ); return ; }
//获取当前http请求 servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes(); httpservletrequest request = attributes.getrequest();
string token = request.getheader(appconst.auth_token);
bizresult<string> bizresult = authtokenservice.powercheck(token);
system.out.println(serializeutil.serialize(bizresult));
if (bizresult.getisok() == true ) { powerlogger.info( "方法认证通过" ); } else { throw new exception(bizresult.getmessage()); } }
/** * 类下面的所有方法执行前进行请求合法性认证 (后) */ @before ( "requestmapping() && methodpointcut()" ) public void dobefore(joinpoint joinpoint) throws exception {
powerlogger.info( "类认证开始..." );
annotation[] annotations = joinpoint.getsignature().getdeclaringtype().getannotationsbytype(authorized. class );
if (annotations == null || annotations.length == 0 ) { powerlogger.info( "类不需要认证" ); return ; }
//获取当前http请求 servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes(); httpservletrequest request = attributes.getrequest();
string token = request.getheader(appconst.auth_token);
bizresult<string> bizresult = authtokenservice.powercheck(token);
system.out.println(serializeutil.serialize(bizresult));
if (bizresult.getisok() == true ) { powerlogger.info( "类认证通过" ); } else { throw new exception(bizresult.getmessage()); } }
} |
需要注意的是,对类和方法上的authorized处理,定义了重载的处理方法dobefore。authtokenservice和上文介绍的处理逻辑一样,如果安全认证不通过,则抛出异常。
如果我们在类上或者方法上都加了authorized注解,不会进行重复安全认证,请放心使用。
4、统一异常处理
上文已经提到过,对所有发生异常的api,都返回统一格式的报文至调用方。主要代码大致如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
package com.power.demo.controller.exhandling;
import com.power.demo测试数据mon.errorinfo; import org.springframework.http.httpstatus; import org.springframework.web.bind.annotation.controlleradvice; import org.springframework.web.bind.annotation.exceptionhandler; import org.springframework.web.bind.annotation.responsebody;
import javax.servlet.http.httpservletrequest; import java.util.date;
/** * 全局统一异常处理增强 **/ @controlleradvice public class globalexceptionhandler {
/** * api统一异常处理 **/ @exceptionhandler (value = exception. class ) @responsebody public errorinfo<exception> jsonapierrorhandler(httpservletrequest request, exception e) { errorinfo<exception> errorinfo = new errorinfo<>(); try { system.out.println( "统一异常处理..." ); e.printstacktrace();
throwable innerex = e.getcause(); while (innerex != null ) { //innerex.printstacktrace(); if (innerex.getcause() == null ) { break ; } innerex = innerex.getcause(); }
if (innerex == null ) { errorinfo.setmessage(e.getmessage()); errorinfo.seterror(e.tostring()); } else { errorinfo.setmessage(innerex.getmessage()); errorinfo.seterror(innerex.tostring()); }
errorinfo.setdata(e); errorinfo.settimestamp( new date()); errorinfo.setstatus(httpstatus.internal_server_error.value()); //500错误 errorinfo.seturl(request.getrequesturl().tostring()); errorinfo.setpath(request.getservletpath());
} catch (exception ex) { ex.printstacktrace();
errorinfo.setmessage(ex.getmessage()); errorinfo.seterror(ex.tostring()); }
return errorinfo; }
} |
认证不通过的api调用结果如下:
异常的整个堆栈可以非常非常方便地帮助我们排查到问题。
我们再结合上文来看安全认证的时间先后,根据理论分析和实践发现,过滤器filter先于拦截器interceptor先于自定义authorized方法认证先于authorized类认证。
到这里,我们发现通过aop框架aspectj,一个@aspect注解外加几个方法几十行业务代码,就可以轻松实现对rest api的拦截处理。
那么为什么会有@pointcut,既然有@before,是否有@after?
其实上述简易安全认证功能实现的过程主要利用了spring的aop特性。
下面再简单介绍下aop常见概念(主要参考spring实战),加深理解。aop概念较多而且比较乏味,经验丰富的老鸟到此就可以忽略这一段了。
二、aop
1、概述
aop(aspect oriented programming),即面向切面编程,可以处理很多事情,常见的功能比如日志记录,性能统计,安全控制,事务处理,异常处理等。
aop可以认为是一种更高级的[复用]技术,它是oop(object oriented programming,面向对象编程)的补充和完善。aop的理念,就是将分散在各个业务逻辑代码中相同的代码通过横向切割的方式抽取到一个独立的模块中。将相同逻辑的重复代码横向抽取出来,使用动态代理技术将这些重复代码织入到目标对象方法中,实现和原来一样的功能。这样一来,我们在写业务逻辑时就只关心业务代码。
oop引入封装、继承、多态等概念来建立一种对象层次结构,用于模拟公共行为的一个集合。不过oop允许开发者定义纵向的关系,但并不适合定义横向的关系,例如日志功能。日志代码往往横向地散布在所有对象层次中,而与它对应的对象的核心功能毫无关系对于其他类型的代码,如安全性、异常处理和透明的持续性也都是如此,这种散布在各处的无关的代码被称为横切(cross cutting),在oop设计中,它导致了大量代码的重复,而不利于各个模块的重用。
aop技术恰恰相反,它利用一种称为"横切"的技术,剖解开封装的对象内部,并将那些影响了多个类的公共行为封装到一个可重用模块,并将其命名为"aspect",即切面。
所谓"切面",简单说就是那些与业务无关,却为业务模块所共同调用的逻辑或责任封装起来,便于减少系统的重复代码,降低模块之间的耦合度,并有利于未来的可操作性和可维护性。
使用"横切"技术,aop把软件系统分为两个部分:核心关注点和横切关注点。
业务处理的主要流程是核心关注点,与之关系不大的部分是横切关注点。横切关注点的一个特点是,它们经常发生在核心关注点的多处,而各处基本相似,比如权限认证、日志、事务。aop的作用在于分离系统中的各种关注点,将核心关注点和横切关注点分离开来。
2、aop术语
深刻理解aop,要掌握的术语可真不少。
target:目标类,需要被代理的类,如:userservice
advice:通知,所要增强或增加的功能,定义了切面的[什么]和[何时],模式有before、after、after-returning,、after-throwing和around
join point:连接点,应用执行过程中,能够插入切面的所有[点](时机)
pointcut:切点,实际运行中,选择插入切面的连接点,即定义了哪些点得到了增强。切点定义了切面的[何处]。我们通常使用明确的类和方法名称,或是利用正则表达式定义所匹配的类和方法名称来指定这些切点。
aspect:切面,把横切关注点模块化为特殊的类,这些类称为切面,切面是通知和切点的结合。通知和切点共同定义了切面的全部内容:它是什么,在何时和何处完成其功能
introduction:引入,允许我们向现有的类添加新方法或属性
weaving:织入,把切面应用到目标对象并创建新的代理对象的过程,切面在指定的连接点被织入到目标对象中。在目标对象的生命周期里有多个点可以进行织入:编译期、类加载期、运行期
下面参考自网上图片,可以比较直观地理解上述这几个aop术语和流转过程。
3、aop实现
(1)动态代理
使用动态代理可以为一个或多个接口在运行期动态生成实现对象,生成的对象中实现接口的方法时可以添加增强代码,从而实现aop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.lang.reflect.invocationhandler; import java.lang.reflect.method; import java.lang.reflect.proxy;
/** * 动态代理类 */ public class dynamicproxy implements invocationhandler {
/** * 需要代理的目标类 */ private object target;
/** * 写法固定,aop专用:绑定委托对象并返回一个代理类 * * @param target * @return */ public object bind(object target) { this .target = target; return proxy.newproxyinstance(target.getclass().getclassloader(), target.getclass().getinterfaces(), this ); }
/** * 调用 invocationhandler接口定义方法 * * @param proxy 指被代理的对象。 * @param method 要调用的方法 * @param args 方法调用时所需要的参数 */ @override public object invoke(object proxy, method method, object[] args) throws throwable { object result = null ; // 切面之前执行 system.out.println( "[动态代理]切面之前执行" );
// 执行业务 result = method.invoke(target, args);
// 切面之后执行 system.out.println( "[动态代理]切面之后执行" );
return result; }
} |
缺点是只能针对接口进行代理,同时由于动态代理是通过反射实现的,有时可能要考虑反射调用的开销,否则很容易引发性能问题。
(2)字节码生成
动态字节码生成技术是指在运行时动态生成指定类的一个子类对象(注意是针对类),并覆盖其中特定方法,覆盖方法时可以添加增强代码,从而实现aop。
最常用的工具是cglib:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import org.springframework.cglib.proxy.enhancer; import org.springframework.cglib.proxy.methodinterceptor; import org.springframework.cglib.proxy.methodproxy;
import java.lang.reflect.method;
/** * 使用cglib动态代理 * <p> * jdk中的动态代理使用时,必须有业务接口,而cglib是针对类的 */ public class cglibproxy implements methodinterceptor {
private object target;
/** * 创建代理对象 * * @param target * @return */ public object getinstance(object target) { this .target = target; enhancer enhancer = new enhancer(); enhancer.setsuperclass( this .target.getclass()); // 回调方法 enhancer.setcallback( this ); // 创建代理对象 return enhancer.create(); }
@override public object intercept(object proxy, method method, object[] args, methodproxy methodproxy) throws throwable { object result = null ; system.out.println( "[cglib]切面之前执行" );
result = methodproxy.invokesuper(proxy, args);
system.out.println( "[cglib]切面之后执行" );
return result; }
} |
(3)定制的类加载器
当需要对类的所有对象都添加增强,动态代理和字节码生成本质上都需要动态构造代理对象,即最终被增强的对象是由aop框架生成,不是开发者new出来的。
解决的办法就是实现自定义的类加载器,在一个类被加载时对其进行增强。
jboss就是采用这种方式实现aop功能。
这种方式目前只是道听途说,本人没有在实际项目中实践过。
(4)代码生成
利用工具在已有代码基础上生成新的代码,其中可以添加任何横切代码来实现aop。
(5)语言扩展
可以对构造方法和属性的赋值操作进行增强,aspectj是采用这种方式实现aop的一个常见的java语言扩展。
比较:根据日志,上述流程的执行顺序依次为:过滤器、拦截器、aop方法认证、aop类认证
附:记录api日志
最后通过记录api日志,记录日志时加入api耗时统计(其实我们在开发.net应用的过程中通过aop这种记录日志的方式也已经是标配),加深上述aop的几个核心概念的理解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package com.power.demo.controller.tool;
import com.power.demo.apientity.baseapirequest; import com.power.demo.apientity.baseapiresponse; import com.power.demo.util.datetimeutil; import com.power.demo.util.serializeutil; 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.annotation.pointcut; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.stereotype测试数据ponent; import org.springframework.util.stopwatch;
/** * 服务日志切面,主要记录接口日志及耗时 **/ @aspect @component public class svclogaspect {
@pointcut ( "@annotation(org.springframework.web.bind.annotation.requestmapping)" ) public void requestmapping() { }
@pointcut ( "execution(* com.power.demo.controller.*controller.*(..))" ) public void methodpointcut() { }
@around ( "requestmapping() && methodpointcut()" ) public object around(proceedingjoinpoint pjd) throws throwable {
system.out.println( "spring aop方式记录服务日志" );
object response = null ; //定义返回信息
baseapirequest baseapirequest = null ; //请求基类
int index = 0 ;
signature cursignature = pjd.getsignature();
string classname = cursignature.getclass().getname(); //类名
string methodname = cursignature.getname(); //方法名
logger logger = loggerfactory.getlogger(classname); //日志
stopwatch watch = datetimeutil.startnew(); //用于统计调用耗时
// 获取方法参数 object[] reqparamarr = pjd.getargs(); stringbuffer sb = new stringbuffer(); //获取请求参数集合并进行遍历拼接 for (object reqparam : reqparamarr) { if (reqparam == null ) { index++; continue ; } try { sb.append(serializeutil.serialize(reqparam));
//获取继承自baseapirequest的请求实体 if (baseapirequest == null && reqparam instanceof baseapirequest) { index++; baseapirequest = (baseapirequest) reqparam; }
} catch (exception e) { sb.append(reqparam.tostring()); } sb.append( "," ); }
string strparam = sb.tostring(); if (strparam.length() > 0 ) { strparam = strparam.substring( 0 , strparam.length() - 1 ); }
//记录请求 logger.info(string.format( "【%s】类的【%s】方法,请求参数:%s" , classname, methodname, strparam));
response = pjd.proceed(); // 执行服务方法
watch.stop();
//记录应答 logger.info(string.format( "【%s】类的【%s】方法,应答参数:%s" , classname, methodname, serializeutil.serialize(response)));
// 获取执行完的时间 logger.info(string.format( "接口【%s】总耗时(毫秒):%s" , methodname, watch.gettotaltimemillis()));
//标准请求-应答模型
if (baseapirequest == null ) {
return response; }
if ((response != null && response instanceof baseapiresponse) == false ) {
return response; }
system.out.println( "spring aop方式记录标准请求-应答模型服务日志" );
object request = reqparamarr[index];
baseapiresponse bizresp = (baseapiresponse) response; //记录日志 string msg = string.format( "请求:%s======应答:%s======总耗时(毫秒):%s" , serializeutil.serialize(request), serializeutil.serialize(response), watch.gettotaltimemillis());
if (bizresp.getisok() == true ) { logger.info(msg); } else { logger.error(msg); //记录错误日志 }
return response; }
} |
标准的请求-应答模型,我们都会定义请求基类和应答基类,本文示例给到的是baseapirequest和baseapiresponse,搜集日志时,可以对错误日志加以区分特殊处理。
注意上述代码中的@around环绕通知,参数类型是proceedingjoinpoint,而前面第一个示例的@before前置通知,参数类型是joinpoint。
下面是aspectj通知和增强的5种模式:
@before前置通知,在目标方法执行前实施增强,请求参数joinpoint,用来连接当前连接点的连接细节,一般包括方法名和参数值。在方法执行前进行执行方法体,不能改变方法参数,也不能改变方法执行结果。
@after 后置通知,请求参数joinpoint,在目标方法执行之后,无论是否发生异常,都进行执行的通知。在后置通知中,不能访问目标方法的执行结果(因为有可能发生异常),不能改变方法执行结果。
@afterreturning 返回通知,在目标方法执行后实施增强,请求参数joinpoint,其能访问方法执行结果(因为正常执行)和方法的连接细节,但是不能改变方法执行结果。(注意和后置通知的区别)
@afterthrowing 异常通知,在方法抛出异常后实施增强,请求参数joinpoint,throwing属性代表方法体执行时候抛出的异常,其值一定与方法中exception的值需要一致。
@around 环绕通知,请求参数proceedingjoinpoint,环绕通知类似于动态代理的全过程,proceedingjoinpoint类型的参数可以决定是否执行目标方法,而且环绕通知必须有返回值,返回值即为目标方法的返回值。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:http://blog.51cto测试数据/13932491/2312412
查看更多关于Spring Boot使用AOP实现REST接口简易灵活的安全认证的方法的详细内容...