Springcloud Zuul Filter return value intercept

Source: Internet
Author: User

Zuul as a gateway service, is the other services to the external transit station, through the Zuul request forwarding. This involves some of the data can not be returned intact, such as the communication between the service credentials, the user's encrypted information and so on.

The code in this article has been submitted to: Https://gitee.com/cmlbeliever/springcloud Welcome to Star
Implementation class in: Api-getway project under the Com.cml.springcloud.api.filter.AuthResponseFilter

For example, the user Service provides a login interface, the user name password is correct after the return of a token, the token as a User Service pass, then the user login after the successful token will need to encrypt or prevent tampering processing. Before reaching the user Service other interfaces, it is necessary to verify token, the illegal token does not need to forward to the user Service, directly in the gateway layer to return information.

To modify the information returned by the service, you need to use a Zuul filter. You only need to inherit zuulfilter to implement the necessary methods.

Zuul provides a default of four filter types, identified by the FilterType method pre: You can call the route before the request is routed: called Post when the request is routed: Called after the route and error filter Error: Called when processing a request

The order in which the filters are executed is sorted by the Filterorder method, and the smaller the value the higher the precedence. Filterconstants defines the execution order and routing type of the default filters for some columns, and most of the constants that need to be used are here.

As illustrated in the example, only the login interface needs to be intercepted, so you only need to intercept the login request (/user/login). The Shouldfilter method of the filter can be used to determine if interception is required.

Since the data modifications are made after the successful User service, the type of interceptor is post type. The implementation of the entire class is as follows:

public class Authresponsefilter extends Abstractzuulfilter {private static final String Response_key_token = "TOKEN"
    ;
    @Value ("${system.config.authfilter.authurl}") Private String AuthUrl;

    @Value ("${system.config.authfilter.tokenkey}") Private String Tokenkey = Response_key_token;

    @Autowired private Authapi Authapi;
        @Override public boolean shouldfilter () {RequestContext context = Getcurrentcontext ();
    Return Stringutils.equals (Context.getrequest (). Getrequesturi (). toString (), authurl);

            } @Override public Object run () {try {RequestContext context = Getcurrentcontext ();
            InputStream stream = Context.getresponsedatastream ();

            String BODY = streamutils.copytostring (stream, Charset.forname ("UTF-8"));
                if (Stringutils.isnotblank (body)) {Gson Gson = new Gson (); @SuppressWarnings ("Unchecked") map<string, string> ResUlt = Gson.fromjson (body, map.class); if (Stringutils.isnotblank (Result.get (Tokenkey))) {Authmodel Authresult = Authapi.encodetoken (result.
                    Get (Tokenkey)); if (Authresult.getstatus ()! = HTTPSERVLETRESPONSE.SC_OK) {throw new IllegalArgumentException (auth
                    Result.geterrmsg ());
                    } String Accesstoken = Authresult.gettoken ();
                Result.put (Tokenkey, Accesstoken);
            } BODY = Gson.tojson (result);
        } context.setresponsebody (body);
        } catch (IOException e) {rethrowruntimeexception (e);
    } return null;
    } @Override Public String FilterType () {return filterconstants.post_type;
    } @Override public int filterorder () {return filterconstants.send_response_filter_order-2; }

}

Config file, add the authorization URL and the key to return token:
System.config.authfilter.authurl=/user/login
System.config.authfilter.tokenkey=token
Context.setresponsebody (body); This code is the core that modifies the return data through this method.

When the user logs in successfully, according to the token returned, token encryption through the licensing service, where the encryption is using JWT. To prevent users from tampering with information, illegal requests can be intercepted directly at the gateway layer.

About the Zuul filter implementation process, here do not need to explain, the source of a look will know, Zuulservletfilter:

@Override public void DoFilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain ) throws IOException, Servletexception {try {init (httpservletrequest) ServletRequest, (httpservletr
            Esponse) servletresponse);
            try {prerouting ();
                } catch (Zuulexception e) {error (E);
                Postrouting ();
            Return }//Only forward onto to the chain if a zuul response are not being sent if (! Requestcontext.getcurrentcontext (). Sendzuulresponse ()) {Filterchain.dofilter (ServletRequest, ServletRespo
                NSE);
            Return
            } try {routing ();
                } catch (Zuulexception e) {error (E);
                Postrouting ();
            Return
            } try {postrouting ();
         } catch (Zuulexception e) {       Error (E);
            Return }} catch (Throwable e) {error (New Zuulexception (E, $, "uncaught_exception_from_filter_" + E.GETCLA
        SS (). GetName ()));
        } finally {Requestcontext.getcurrentcontext (). unset (); }
    }

Method Description:
Preroute: Performing a pre-type filter
Postroute: Performing a Post type filter
Route: A filter that executes the route type
Error: Executing a filter of type error

The forwarding of the request can be terminated by Context.setsendzuulresponse (false), but only in filters of the pre type.

about how to stop a filter:
Only pre-type filters support terminating forwarding, and other filters are executed sequentially, and pre-type filters can terminate forwarding only after all pre-filters have been executed, and no termination filters continue. See Zuulservletfilter Source code:

     Only forward onto to the chain if a zuul response are not being sent
            if (! Requestcontext.getcurrentcontext (). Sendzuulresponse ()) {
                Filterchain.dofilter (ServletRequest, Servletresponse);
                return;
            }

The code in this article has been submitted to: Https://gitee.com/cmlbeliever/springcloud Welcome to Star
Implementation class in: Api-getway project under the Com.cml.springcloud.api.filter.AuthResponseFilter

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.