How can I configure Lagom framework to work with CORS?

518 Views Asked by At

How can I configure Lagom framework to work with CORS request (method request 'options').

2

There are 2 best solutions below

1
On BEST ANSWER

To allow a Lagom service written in Java to work with CORS, you'll need to implement a CORS filter per Play:

package example.service.impl


import play.filters.cors.CORSFilter;
import play.http.DefaultHttpFilters;

import javax.inject.Inject;

// See https://playframework.com/documentation/2.5.x/CorsFilter
public class MyCORSFilter extends DefaultHttpFilters {
    @Inject
    public MyCORSFilter(CORSFilter corsFilter) {
        super(corsFilter);
    }
}

and then in your application.conf, you'll need to add the filter:

play.http.filters = "example.service.impl.MyCORSFilter"

// To properly setup the CORSFilter, please refer to https://playframework.com/documentation/2.5.x/CorsFilter
// This example is only meant to show what's required for Lagom to use CORS.
play.filters.cors {
  // review the values of all these settings to fulfill your needs. These values are not meant for production.
  pathPrefixes = ["/api"]
  allowedOrigins = null
  allowedHttpMethods = null
  allowedHttpHeaders = null
  exposedHeaders = []
  supportsCredentials = false
  preflightMaxAge = 6 hour
}

For more info, see the example CORS service and the Play docs.

1
On

I have enabled CORS in lagom for one of my projects in this way.

Define a method in service class to handle OPTIONS calls.

ServiceCall<NotUsed, Done> options();

Implement the method in the service-impl class.

@Override
public ServiceCall<NotUsed, Done> options() {
    return request -> CompletableFuture.completedFuture(Done.getInstance());
}

Define the options call in the descriptor. As an example, assume that the actual call is,

GET /api/v0.1/user

The service descriptor should look like this:

@Override
default Descriptor descriptor() {
    // @formatter:off
    return named("notification").withCalls(
            restCall(Method.GET, "/api/v0.1/user", this::getUser),
            restCall(Method.OPTIONS, "/api/v0.1/user", this::options)

    ).withAutoAcl(true).withHeaderFilter(new CORSHeaderFilter());
    // @formatter:on
}

Note that it has a header filter attached using,

.withHeaderFilter(new CORSHeaderFilter()) 

CORSHeaderFilter Class should look like this.

import com.lightbend.lagom.javadsl.api.transport.HeaderFilter;
import com.lightbend.lagom.javadsl.api.transport.Method;
import com.lightbend.lagom.javadsl.api.transport.RequestHeader;
import com.lightbend.lagom.javadsl.api.transport.ResponseHeader;

public class CORSHeaderFilter implements HeaderFilter {

    @Override
    public RequestHeader transformClientRequest(RequestHeader request) {
        return request;
    }

    @Override
    public RequestHeader transformServerRequest(RequestHeader request) {
        return request;
    }

    @Override
    public ResponseHeader transformServerResponse(ResponseHeader response, RequestHeader request) {
        ResponseHeader modifiedResponse = response.withHeader("Access-Control-Allow-Origin", "*");
        if (Method.OPTIONS.equals(request.method())) {
            modifiedResponse = modifiedResponse.withStatus(204).withHeader("Access-Control-Allow-Headers",
                    "Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With" +
                            ",If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range").
                    withHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PATCH").
                    withHeader("Access-Control-Max-Age", "1728000");
        }
        return modifiedResponse;
    }

    @Override
    public ResponseHeader transformClientResponse(ResponseHeader response, RequestHeader request) {
        ResponseHeader modifiedResponse = response.withHeader("Access-Control-Allow-Origin", "*");
        if (Method.OPTIONS.equals(request.method())) {
            modifiedResponse = modifiedResponse.withStatus(204).withHeader("Access-Control-Allow-Headers",
                    "Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With" +
                            ",If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range").
                    withHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PATCH").
                    withHeader("Access-Control-Max-Age", "1728000");
        }
        return modifiedResponse;
    }
}

Whenever you add a new endpoint, make sure to add the OPTIONS version of it as well.