Configuring CORS (Cross-Origin Resource Sharing) in Micronaut

Introduction:

Cross-Origin Resource Sharing (CORS) is an important security feature implemented by web browsers to prevent malicious websites from accessing resources on other domains. In a Micronaut application, configuring CORS properly ensures that your APIs can be accessed securely from web applications hosted on different origins. In this blog post, we’ll explore how to configure CORS in a Micronaut application to allow safe cross-origin requests.

Understanding CORS:

Before diving into configuration, let’s briefly understand how CORS works. When a web browser makes a cross-origin request (i.e., a request to a different domain, port, or protocol), it sends an HTTP request with an Origin header indicating the origin of the request. The server then decides whether to allow the request based on the presence of CORS headers in the response.

Configuring CORS in Micronaut:

Micronaut provides built-in support for configuring CORS through properties or annotations. There are two main approaches to configuring CORS: global configuration and per-route configuration.

Global Configuration: To configure CORS globally for all routes in your Micronaut application, you can use application properties. Simply add the following properties to your application.yml or application.properties file:

micronaut:
  server:
    cors:
      enabled: true
      configurations:
        default:
          allowed-origins: "*"
          allowed-methods: "GET, POST, PUT, DELETE"
          allowed-headers: "*"
          exposed-headers: "Location"
          max-age: "1800"
          allow-credentials: true

In this configuration:

  • allowed-origins specifies the origins allowed to make cross-origin requests.
  • allowed-methods specifies the HTTP methods allowed in cross-origin requests.
  • allowed-headers specifies the headers allowed in cross-origin requests.
  • exposed-headers specifies the headers exposed to the client.
  • max-age specifies the maximum age (in seconds) of preflight requests.
  • allow-credentials specifies whether credentials (e.g., cookies) are allowed in cross-origin requests.

Related Post