Implementation of SpringMVC interface permission interceptor

background

       Each website will be connected with other companies or platforms, and some companies will also have interfaces to call each other. However, the direct opening of the interface is not secure, and there must be a corresponding token to ensure security. When is the token verified? Naturally, when the request comes, before the backend receives it.

       Java web development has a module specially designed to handle this kind of request - the interceptor. The interceptor will verify whether the request conforms to the rules before it can be truly received. Then, as long as the token is correct in the interceptor, illegal requests can be filtered out. Even control access by controlling the permissions of the token.

principle

       The interceptor provides three methods: preHandle, postHandle and afterCompletion. The preHandle is called before calling the specific method of the controller, the postHandle is called after the specific method is completed, and the afterCompletion is called after the rendering of the page is completed. At this point, the rendering of the entire page is completed. That is to say, we record the start time in preHandle, the end time in afterCompletion record, or the time when the entire page is generated.

       Obviously, what we need to intercept this time is the interface permission. Only those with permission can do subsequent operations, that is, use the preHandle method.

steps and processes

step:

Step 1: Customize a class that implements the Interceptor interface, or inherit the abstract class AbstractInterceptor. The second step of the HandlerInterceptor interface is inherited
    : register the defined interceptor in the configuration file.
    Step 3: Write business logic in the Controller that needs to be used

process:

Implementation

1 Custom interceptor class that implements the HandlerInterceptor interface

2 Implement the preHandle method, which checks whether app_id and app_secret are legal

3 Register the interceptor in the configuration class and define the rules that take effect

4 Write Controller code

core code

Interceptor OpenIntercept:

@Component	//表示这是一个组件,可以实现依赖注入
public class OpenIntercept  implements HandlerInterceptor{	
	// 校验的数据存在数据库中,需要查询数据库
	@Autowired
	AppSourceMapper appSourceMapper; 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取指定的参数数据,用于校验使用
		String app_id = request.getParameter("app_id");
		String app_secret = request.getParameter("app_secret");
		System.out.println(request.getRemoteAddr());
		// 校验是否合法
		if(StringUtils.isNotBlank(app_id)&& StringUtils.isNotBlank(app_secret)&& checkAppSourceIsExsist(app_id,app_secret)){
			return true;	//合法通过
		} else{
			//非法给出提示
			response.setCharacterEncoding("UTF-8");
			response.getOutputStream().write(ResultUtils.error(-1, "您无操作此接口的权限!").getBytes());
			return false;
		}
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	// 校验数据库是否存在令牌对
	private boolean checkAppSourceIsExsist(String app_id,String app_secret){
		return  appSourceMapper.countByAppIdAndSecret(app_id, app_secret)>0?true:false;
	}
}

 

Configuration class CoreConfiguration 

public class CoreConfiguration extends WebMvcConfigurerAdapter{
	@Autowired
	OpenIntercept openIntercept; 
    // 注册拦截器
	public void addInterceptors(InterceptorRegistry registry) {
        // 注册包括拦截器和拦截的路径,可以使用统配表达式
		registry.addInterceptor(openIntercept).addPathPatterns("/open/**");
	 }
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }
    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(responseBodyConverter());
    }
    @Override
    public void configureContentNegotiation(
            ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(false);
    }
}

    If you think this article is good, you can like it, and if you think it is not good, you can make suggestions or comments, and make progress and grow together! ! !

    Welcome to email to discuss [email protected]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325238171&siteId=291194637