Introduction to the

The full name of CORS is cross-domain resource sharing. It is an HTTP-header-based detection mechanism. By controlling THE HTTP-header, you can manage the permission 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

Those familiar with CORS should know that all CORS operations are implemented on top of the HTTP protocol by controlling HTTP headers. Therefore, if you want to implement CORS support on the server side, in fact, the HTTP protocol header is set up to complete.

For your convenience, Netty provides a CorsConfig class to unify CORS headers.

Take a look at the properties 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;Copy the code

These attributes correspond one to one to the HTTP header Settings of CORS. For example, “origins” means allowed sources, and “anyOrigin” means allowed all sources.

This corresponds to the following Settings:

Origin: <origin>
Copy the code

ExposeHeaders corresponds to access-Control-expose-headers, indicating the header information that the server allows the client to Access while obtaining CORS resources. The format is as follows:

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

AllowCredentials: Indicates whether CORS permission authentication is enabled. Indicates whether the server accepts requests with the credentials field from the client. When used in preflight requests, it indicates whether the credentials are supported in subsequent real requests. The format is as follows:

Access-Control-Allow-Credentials: true
Copy the code

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

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

AllowedRequestHeaders are header fields that can be used in preflight requests. The format is as follows:

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

But when a client sends surrounding methods to a server, to be safe because the server is not always able to accept these OPTIONS methods, the client needs to send a preflighted request, wait for a response from the server, and then send a real request. Let’s take an example. PreflightHeaders refer to the preflight headers that the server allows.

ShortCircuit Indicates whether the request is a valid CORS request and returns true if the request is rejected.

CorsConfigBuilder

CorsConfig is used to represent the configuration class of Cors. How to construct this configuration class? Let’s look at the CorsConfig constructor:

    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;
    }
Copy the code

You can see that CorsConfig is constructed through CorsConfigBuilder. This is done by setting various properties in CorsConfigBuilder. CorsConfigBuilder provides a variety of methods for setting properties.

CorsConfig can be constructed as follows:

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

CorsHandler

With corsConfig, we also need to configure this config in Netty’s handler. Netty provides a CorsHandler class to handle corsConfig. This class is called CorsHandler.

First look at the CorsHandler constructor:

    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;
    }
Copy the code

CorsHandler has two constructors, one for passing in CorsConfig and the other for passing in a list of CorsConfig.

CorsHandler works by processing the responseHeader at channelRead and setting the CORS header.

Netty support for CORS

Above we have talked about the core class and method of CORS in Netty, the last step is to add the cORS support class to netty pipeline, its 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());
    }
Copy the code

conclusion

Cors is relatively simple, and Netty also provides support for the method of living. You can use it directly.

Learn -netty4 for an example of this article

This article is available at www.flydean.com/22-netty-co…

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!