SpringBoot allows you to quickly set the interceptor and implement permission verification.

Source: Internet
Author: User

SpringBoot allows you to quickly set the interceptor and implement permission verification.

I. Overview

More and more application scenarios of interceptor, especially after the popularity of slice-oriented programming. What can an interceptor do?

Previously, we mentioned in the Introduction of Agent that counts the time consumption of function calls. This idea is actually the same as the enhancement of AOP.

In general, the scenario is as follows:

  1. Function enhancement: for example, parameter check or result Filtering for a function. You can even authenticate functions.
  2. Performance monitoring: collects statistics on function performance.
  3. Log hitting: for example, logging PV statistics before a user logs on to the function.

And others.

Ii. Spring interceptor

In SpringMVC or SpringBoot, the interceptor has to mention:
Org. springframework. web. servlet. handler. HandlerInterceptorAdapter

Public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor {// run @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true ;} // It is executed after the target method is executed, but before the request is returned, we can still modify ModelAndView @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} // execute @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) after the request has been returned) throws Exception {} // used to process asynchronous requests. When the Controller has an asynchronous request method, this method @ Override public void afterConcurrentHandlingStarted (HttpServletRequest request, HttpServletResponse response, Object handler) is triggered) throws Exception {}}

3. Implement an interceptor to verify simple Permissions

1. Customize a permission annotation @ Auth

@Inherited@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Auth {  String user() default "";}
  1. @ Inherited: when using this custom annotation, if the annotation is on the class, the subclass automatically inherits this annotation. Otherwise, the subclass does not inherit this annotation. Remember that the annotation declared by using Inherited is valid only when used on the class, and other annotations such as methods and attributes are invalid.
  2. @ Target: the location where the annotation can be placed. Common locations are: TYPE = enumeration or annotation, FIELD = FIELD, METHOD = METHOD, PARAMETER = function PARAMETER list, CONSTRUCTOR = CONSTRUCTOR, LOCAL_VARIABLE = other locations on local variables.
  3. @ Retention: lifecycle of the annotation. Common examples are: SOURCE = SOURCE code period; CLASS = bytecode period (Compiled); RUNTIME = RUNTIME, which usually requires more.
  4. @ Documentd: generate the annotation document.

2. Add annotations to the Controller method.

After adding the annotation in the previous step, you need to add the Annotation on the method you are using, as shown below.

@RestController@EnableAutoConfigurationpublic class DemoController {  @Auth(user = "admin")  @RequestMapping(value = "/hello", method = RequestMethod.GET)  public String sayHello() {    return "hello world.";  }}

3. Implement interceptor Functions

Requirement: when the user accesses the URL through the/hello URI, it is verified. If the user is admin, the access is allowed; otherwise, the access is rejected. Assume that the user's identity is in the URL parameter.

Idea: we need to verify the user before executing sayHello. If the identity is the same as the identity in the annotation, it is allowed. Therefore, we need to make an article in preHandle.

Difficulty: How do we get the @ Auth Annotation on the Controller method? Looking at the three parameters of PreHandle (), it seems that no annotation in the Controller class can be provided.

In fact, the third parameter handler is generally of the org. springframework. web. method. HandlerMethod type, which contains the annotation information.

Why?

In SpringBoot, the default annotation type is function level, while in SpringMVC, its default type is Controller object level.

Therefore, if SpringMVC needs to be configured in a dispatcher-servlet.xml:
<Bean class = "org. springframework. web. servlet. mvc. method. annotation. RequestMappingHandlerMapping"/>, so that the type is HandlerMethod.

Let's take a look at the specific implementation logic:

@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System. out. println ("preHandle"); if (! Handler. getClass (). isAssignableFrom (HandlerMethod. class) {System. out. println ("cat cast handler to HandlerMethod. class "); return true;} // get the annotation Auth auth = (HandlerMethod) handler ). getMethod (). getAnnotation (Auth. class); if (auth = null) {System. out. println ("cant find @ Auth in this uri:" + request. getRequestURI (); return true;} // retrieve the user identity from the parameter and verify String admin = auth. user (); if (! Admin. equals (request. getParameter ("user") {System. out. println ("permission denied"); response. setStatus (403); return false;} return true ;}

In fact, the implementation logic is two points: retrieve the identity from the parameter and compare it with that in the annotation.

4. Configure the interceptor

So how can we make this interceptor take effect?

At this time, we need to configure: WebMvcConfigurerAdapter

The specific implementation is as follows:

@Configurationpublic class ConfigAdapter extends WebMvcConfigurerAdapter {  @Override  public void addInterceptors(InterceptorRegistry registry) {    registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/hello");  }}

Note: There are two points to note: one is the annotation @ Configuration, so that the SpringBoot service can discover this Configuration; the other is the Configuration matching item, here we intercept "/hello. ("/**" Is used to block all access requests)

Iv. Run

Access http: // 127.0.0.1: 8080/hello? User = admin.

For the code in this article, see: https://github.com/hawkingfoo/springboot-interceptor

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.