现在我们有三个服务:分别是用户服务、订单服务和产品服务。用户如果购买产品,则需要调用产品服务生成订单,那么我们在这个调用过程中有必要鉴权吗?答案是否定的,因为这些资源服务放在内网环境中,完全不用考虑安全问题。
二、思路如果要想实现这个功能,我们则需要来区分这两种请求,来自网关的请求进行鉴权,而服务间的请求则直接调用。
是否可以给接口增加一个参数来标记它是服务间调用的请求?
这样虽然可以实现两种请求的区分,但是实际中不会这么做。一般情况下服务间调用和网关请求的数据接口是同一个接口,如果写成两个接口来分别给两种请求调用,这样无疑增加了大量重复代码。也就是说我们一般不会通过改变请求参数的个数来实现这两种服务的区分。
虽然不能增加请求的参数个数来区分,但是我们可以给请求的header中添加一个参数用来区分。这样完全可以避免上面提到的问题。
三、实现 3.1 自定义注解我们自定义一个inner的注解,然后利用aop对这个注解进行处理
1@target(elementtype.method)
2@retention(retentionpolicy.runtime)
3@documented
4public @interface inner {
5 /**
6 * 是否aop统一处理
7 */
8 boolean value() default true;
9}
1@aspect
2@component
3public class inneraspect implements ordered {
4
5 private final logger log = loggerfactory.getlogger(inneraspect.class);
6
7 @around(@annotation(inner))
8 public object around(proceedingjoinpoint point, inner inner) throws throwable {
9 string header = servletutils.getrequest().getheader(securityconstants.from);
10 if (inner.value() && !stringutils.equals(securityconstants.from_in, header)){
11 log.warn(访问接口 {} 没有权限, point.getsignature().getname());
12 throw new accessdeniedexception(access is denied);
13 }
14 return point.proceed();
15 }
16
17 @override
18 public int getorder() {
19 return ordered.highest_precedence + 1;
20 }
21}
上面这段代码就是获取所有加了@inner注解的方法或类,判断请求头中是否有我们规定的参数,如果没有,则不允许访问接口。
3.2 暴露url将所有注解了@inner的方法和类暴露出来,允许不鉴权可以方法,这里需要注意的点是如果方法使用pathvariable 传参的,则需要将这个参数转换为*。如果不转换,当成接口的访问路径,则找不到此接口。
1@configuration
2public class permitallurlproperties implements initializingbean, applicationcontextaware{
3
4 private static final pattern pattern = pattern.compile(\\{(.*?)\\});
5 private applicationcontext applicationcontext;
6 private list<string> urls = new arraylist<>();
7 public static final string asterisk = *;
8
9 @override
10 public void afterpropertiesset() {
11 requestmappinghandlermapping mapping = applicationcontext.getbean(requestmappinghandlermapping.class);
12 map<requestmappinginfo, handlermethod> map = mapping.gethandlermethods();
13 map.keyset().foreach(info -> {
14 handlermethod handlermethod = map.get(info);
15 // 获取方法上边的注解 替代path variable 为 *
16 inner method = annotationutils.findannotation(handlermethod.getmethod(), inner.class);
17 optional.ofnullable(method).ifpresent(inner -> info.getpatternscondition().getpatterns()
18 .foreach(url -> urls.add(reutil.replaceall(url, pattern, asterisk))));
19 // 获取类上边的注解, 替代path variable 为 *
20 inner controller = annotationutils.findannotation(handlermethod.getbeantype(), inner.class);
21 optional.ofnullable(controller).ifpresent(inner -> info.getpatternscondition().getpatterns()
22 .foreach(url -> urls.add(reutil.replaceall(url, pattern, asterisk))));
23 });
24 }
25
26 @override
27 public void setapplicationcontext(applicationcontext context) {
28 this.applicationcontext = context;
29 }
30
31 public list<string> geturls() {
32 return urls;
33 }
34
35 public void seturls(list<string> urls) {
36 this.urls = urls;
37 }
38}
在资源服务器中,将请求暴露出来
1public void configure(httpsecurity httpsecurity) throws exception {
2 //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题
3 httpsecurity.headers().frameoptions().disable();
4 expressionurlauthorizationconfigurer<httpsecurity>
5 .expressionintercepturlregistry registry = httpsecurity
6 .authorizerequests();
7 // 将上面获取到的请求,暴露出来
8 permitallurl.geturls()
9 .foreach(url -> registry.antmatchers(url).permitall());
10 registry.anyrequest().authenticated()
11 .and().csrf().disable();
12}
3.3 如何去请求定义一个接口:
1@postmapping(test)
2@inner
3public string test(@requestparam string id){
4 return id;
5}
定义feign远程调用接口
1@postmapping(test)
2mediafodderbean test(@requestparam(id) string id,@requestheader(securityconstants.from) string from);
服务间进行调用,传请求头
1 string id = testservice.test(id, securityconstants.from_in);
四、思考 4.1 安全性上面虽然实现了服务间调用,但是我们将@inner的请求暴露出去了,也就是说不用鉴权既可以访问到,那么我们是不是可以模拟一个请求头,然后在其他地方通过网关来调用呢?
答案是可以,那么,这时候我们就需要对网关中分发的请求进行处理,在网关中写一个全局拦截器,将请求头的form参数清洗。
1@component
2public class requestglobalfilter implements globalfilter, ordered {
3
4 @override
5 public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain) {
6 // 清洗请求头中from 参数
7 serverhttprequest request = exchange.getrequest().mutate()
8 .headers(httpheaders -> httpheaders.remove(securityconstants.from))
9 .build();
10 addoriginalrequesturl(exchange, request.geturi());
11 string rawpath = request.geturi().getrawpath();
12 serverhttprequest newrequest = request.mutate()
13 .path(rawpath)
14 .build();
15 exchange.getattributes().put(gateway_request_url_attr, newrequest.geturi());
16 return chain.filter(exchange.mutate()
17 .request(newrequest.mutate()
18 .build()).build());
19 }
20
21 @override
22 public int getorder() {
23 return -1000;
24 }
25}
4.2 扩展性我们自定义@inner注解的时候,放了一个boolean类型的value(),默认为true。如果我们想让这个请求可以通过网关访问的话,将value赋值为false即可。
1@postmapping(test)
2@inner(value=false)
3public string test(@requestparam string id){
4 return id;
5}
以上就是java怎么实现给接口增加一个参数的详细内容。