Search code examples
javamicroserviceslagom

How can I configure Lagom framework to work with CORS?


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


Solution

  • 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.