Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow authenticators to set CORS headers #14

Merged
merged 1 commit into from
Aug 14, 2023
Merged

Allow authenticators to set CORS headers #14

merged 1 commit into from
Aug 14, 2023

Conversation

adamcooke
Copy link
Contributor

Apia currently always sets very permissive CORS headers because it has never been designed to work with any API which is authenticated on the presence of a cookie and thus CORS has not been issue as authentication should always be provided along with the request.

However, to allow for greater flexibility, this PR introduces the ability for authenticators to set CORS headers on responses without them being overridden later by the default.

The original default remains permissive (and by that I mean the 'Access-Control-Allow-Origin header will return * and the Access-Control-Allow-Methods will also return *.

Usage

To use this, you simply need to define appropriate values within your authenticator.

class MyAuthenticator < Apia::Authenticator

  def call
    cors.origin = "example.com"
    cors.methods = ["GET", "POST"]
    cors.headers = ["X-Custom"]

    # Do other authentication actions as appropriate.
  end
end

The origin can only contain a single hostname so if you support multiple hosts, you'll need to provide logic to return the appropriate value.

class MyAuthenticator < Apia::Authenticator
  

  ALLOWED_ORIGINS = ['example.com', 'example.org']

  def call
    if ALLOWED_ORIGINS.include?(request.host)
      # If the origin is permitted, return the current host name
      # as the origin
      cors.origin = request.host
    else
      # Ensure origin is set to nil otherwise the default value of *
      # will be used allowing all requests.
      cors.origin = nil
    end

    # Other authentication as appropriate...
  end
end

Copy link
Contributor

@jimeh jimeh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not as familiar with Apia's internals as I'd like, but at a glance this looks like it does what it says on the tin.

lib/apia/endpoint.rb Outdated Show resolved Hide resolved
@adamcooke adamcooke merged commit 7afd076 into main Aug 14, 2023
@adamcooke adamcooke deleted the cors branch August 14, 2023 15:46
@replease replease bot mentioned this pull request Aug 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants