Netty series: handling CORS in netty

flydean發表於2021-09-17

Introduction

The full name of CORS is cross-domain resource sharing. It is a mechanism based on HTTP-header detection. By controlling HTTP-header, it can realize the authority management function of cross-domain resources. In the previous CORS detailed article, we have had a basic explanation of CORS.

This article will explain how to implement CORS in netty from the perspective of netty implementation.

CORS configuration on the server

Friends who are familiar with CORS should know that all CORS operations are implemented by controlling HTTP headers on top of the HTTP protocol. Therefore, if you want to implement CORS support on the server side, in fact, it is also completed by various settings of the HTTP protocol header.

In order to facilitate everyone's use, netty provides a CorsConfig class to unify CORS header settings.

First look at the attributes defined in the CorsConfig class:

    private final Set<String> origins;
    private final boolean anyOrigin;
    private final boolean enabled;
    private final Set<String> exposeHeaders;
    private final boolean allowCredentials;
    private final long maxAge;
    private final Set<HttpMethod> allowedRequestMethods;
    private final Set<String> allowedRequestHeaders;
    private final boolean allowNullOrigin;
    private final Map<CharSequence, Callable<?>> preflightHeaders;
    private final boolean shortCircuit;

These attributes and CORS HTTP header settings are one-to-one correspondence. For example, origins means allowed sources, and anyOrigin means all sources are allowed.

It corresponds to the following settings:

Origin: <origin>

ExposeHeaders is one-to-one correspondence with Access-Control-Expose-Headers, which means that the server allows the client to obtain CORS resources and can access the header information at the same time. The format is as follows:

Access-Control-Expose-Headers: <header-name>[, <header-name>]*

allowCredentials indicates whether to enable CORS permission authentication. Indicates whether the server accepts the client's request with the credentials field. If used in a preflight request, it indicates whether the subsequent real request supports credentials, and the format is as follows:

Access-Control-Allow-Credentials: true

AllowedRequestMethods represents the methods allowed to access resources, mainly used in preflight requests. The format is as follows:

Access-Control-Allow-Methods: <method>[, <method>]*

AllowedRequestHeaders is used in preflight request to indicate the header field that can be used as a request. The format is as follows:

Access-Control-Allow-Headers: <header-name>[, <header-name>]*

When the client sends the OPTIONS method to the server, for safety reasons, because the server may not be able to accept these OPTIONS methods, the client needs to send one first
Preflighted requests, wait for the server to respond, wait for the server to confirm, and then send the real request. Let us give an example. preflightHeaders represents the request headers allowed by the server for preflight.

shortCircuit indicates whether the request is a valid CORS request. If the request is rejected, it will return a true value.

CorsConfigBuilder

CorsConfig is used to represent the configuration class of Cors, so how to construct this configuration class? Let's look at the constructor of CorsConfig:

    CorsConfig(final CorsConfigBuilder builder) {
        origins = new LinkedHashSet<String>(builder.origins);
        anyOrigin = builder.anyOrigin;
        enabled = builder.enabled;
        exposeHeaders = builder.exposeHeaders;
        allowCredentials = builder.allowCredentials;
        maxAge = builder.maxAge;
        allowedRequestMethods = builder.requestMethods;
        allowedRequestHeaders = builder.requestHeaders;
        allowNullOrigin = builder.allowNullOrigin;
        preflightHeaders = builder.preflightHeaders;
        shortCircuit = builder.shortCircuit;
    }

You can see that CorsConfig is constructed by CorsConfigBuilder. By setting various properties in CorsConfigBuilder. CorsConfigBuilder provides a variety of methods to set properties.

You can use this method to construct CorsConfig as follows:

CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();

CorsHandler

With corsConfig, we also need to configure this config in netty's handler, netty provides a CorsHandler class to deal with corsConfig specifically, this class is called CorsHandler.

First look at the constructor of CorsHandler:

    public CorsHandler(final CorsConfig config) {
        this(Collections.singletonList(checkNotNull(config, "config")), config.isShortCircuit());
    }

    public CorsHandler(final List<CorsConfig> configList, boolean isShortCircuit) {
        checkNonEmpty(configList, "configList");
        this.configList = configList;
        this.isShortCircuit = isShortCircuit;
    }

CorsHandler has two constructors, one is to pass in CorsConfig, the other is to pass in a list of CorsConfig.

The main working principle of CorsHandler is to process the responseHeader and set the CORS header during channelRead.

netty support for cors

We have already talked about the core classes and methods of cors in netty. The last step is to add the supporting classes of cors to netty's pipeline. The core code is as follows:

    public void initChannel(SocketChannel ch) {

        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpRequestDecoder());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ChunkedWriteHandler());

        CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
        pipeline.addLast(new CorsHandler(corsConfig));

        pipeline.addLast(new CustResponseHandler());
    }

Summarize

Cors is relatively simple, and netty also provides enough method support for it. You can use it directly.

For the examples in this article, please refer to: learn-netty4

This article has been included in http://www.flydean.com/22-netty-cors/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "Program those things", know technology, know you better!

相關文章