In this blog, we are going to discuss about the CORS issue and how it has to be resolved while working with Lagom. So Let’s begin.
What is CORS?
CORS: Cross Origin Resource Sharing
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. By CORS, communications between the same domain will be allowed to users and the communications that are cross-originated will be restricted to a few techniques.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers. So in light words, It blocks the calls made by unknown domains and keeps the paths open only to the known domains. So the security is ensured despite the attacking requests.
What requests use CORS?
This cross-origin sharing standard is used to enable cross-site HTTP requests for:
- Invocations of the XMLHttpRequest or Fetch APIs in a cross-site manner, as discussed above.
- Web Fonts (for cross-domain font usage in @font-face within CSS), so that servers can deploy TrueType fonts that can only be cross-site loaded and used by web sites that are permitted to do so.
- WebGL textures.
- Images/video frames drawn to a canvas using drawImage.
- Stylesheets (for CSSOM access).
- Scripts (for unmuted exceptions).
This CORS implementation is sometimes a typical for the developer. But implementing it correctly removes it once and for all for the given application.
So now the question is how are we going to implement CORS in Lagom framework?
And the solution lies in just 4 steps given by Lagom developers:
Step 1: Include
filters as a dependency on your
filters is a package provided by Play Framework.
com.typesafe.play filters-helpers_2.12 2.6.15
Step 2: Create a class that implements
DefaultHttpFilters and inject Play’s
Step 3: Register that newly created class on your
play.http.filters = "com.fun.assignment.user.impl.Filters"
Step 4: Finally, add an ACL on your
Service.Descriptor matching the
OPTIONS method for the paths you are exposing on your Service Gateway.
Hope this blog would be helpful to you. For more doubts and examples regarding Lagom, feel free to go through our blogs, because we at Knoldus believe in gaining knowledge and growing our skills together.