目录
SpringBoot通过拦截器实现授权码拦截

文章首发于:clawhub.club


需求:个别接口,需要授权码才可以使用,所以要配置拦截器。

首先要实现WebMvcConfigurer接口,Spring的WebMvcConfigurer接口提供了很多方法让我们来定制SpringMVC的配置。
如图:
WebMvcConfigurer.png

实现代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
public class WebConfigurer implements WebMvcConfigurer {

/**
* The Auth code interceptor.
*/
@Autowired
private AuthCodeInterceptor authCodeInterceptor;

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authCodeInterceptor).addPathPatterns("/xxxx");
}
}

从代码中可以看到注入了一个拦截器:AuthCodeInterceptor
其代码实现:

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
@Component
public class AuthCodeInterceptor implements HandlerInterceptor {

/**
* The Auth code service.
*/
@Autowired
private AuthCodeService authCodeService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

//从请求中获取请求体中的authCode,并校验
int flag = authCodeService.checkAuthCodeCore(request.getParameter("authCode"));
String reply;
if (flag == 0) {
//授权码有效
return true;
} else if (flag == 1) {
reply = "{\"code\":\"1\",\"msg\":\"授权码不存在\"}";
} else if (flag == 2) {
reply = "{\"code\":\"2\",\"msg\":\"授权次数不足\"}";
} else {
reply = "{\"code\":\"-2\",\"msg\":\"其他错误\"}";
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(reply);
return false;
}

}

以上就简单实现了拦截特定接口,获取请求参数,之后判断授权码是否可用,可用时,通过,不可用拒绝,并向response中写入响应信息。

关键方法:添加Spring MVC生命周期拦截器,用于控制器方法调用的预处理和后处理。拦截器可以注册为应用于所有请求,也可以限制为URL模式的子集。在这里注册的拦截器只适用于控制器,而不适用于资源处理程序请求。要拦截对静态资源的请求,可以声明MappedInterceptor bean 或者 通过扩展WebMvcConfigurationSupport切换到高级配置模式,然后override resourceHandlerMapping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Add Spring MVC lifecycle interceptors for pre- and post-processing of
* controller method invocations. Interceptors can be registered to apply
* to all requests or be limited to a subset of URL patterns.
* <p><strong>Note</strong> that interceptors registered here only apply to
* controllers and not to resource handler requests. To intercept requests for
* static resources either declare a
* {@link org.springframework.web.servlet.handler.MappedInterceptor MappedInterceptor}
* bean or switch to advanced configuration mode by extending
* {@link org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
* WebMvcConfigurationSupport} and then override {@code resourceHandlerMapping}.
*/
default void addInterceptors(InterceptorRegistry registry) {
}
文章作者: ClawHub
文章链接: https://www.clawhub.club/posts/2019/08/09/JAVA%E5%9F%BA%E7%A1%80/SpringBoot%E9%80%9A%E8%BF%87%E6%8B%A6%E6%88%AA%E5%99%A8%E5%AE%9E%E7%8E%B0%E6%8E%88%E6%9D%83%E7%A0%81%E6%8B%A6%E6%88%AA/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ClawHub的博客
打赏
  • 微信
  • 支付宝
扫一扫关注ClawHub公众号,专注Java、技术分享、面试资源。

评论