The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Mojolicious::Plugin::OpenAPI::Cors - OpenAPI plugin for Cross-Origin Resource Sharing

SYNOPSIS

  package MyApplication::Controller::User;

  sub get_user {

    # Validate incoming CORS request with _validate_cors()
    my $c = shift->openapi->cors_simple("_validate_cors")->openapi->valid_input or return;

    $c->render(openapi => {user => {}});
  }

  sub _validate_cors {
    my ($c, $args) = @_;

    # Check the origin of the request
    if ($args->{origin} =~ m!^https?://whatever.example.com!) {

      # Setting the "Access-Control-Allow-Origin" will mark this request as valid
      $c->res->headers->header("Access-Control-Allow-Origin" => $args->{origin});
    }
  }

DESCRIPTION

Mojolicious::Plugin::OpenAPI::Cors is a plugin for accepting Simple Cross-Origin Resource Sharing requests, by looking at the "Origin" header. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS for more details.

This plugin is loaded by default by Mojolicious::Plugin::OpenAPI.

Note that this plugin currently EXPERIMENTAL! Please let me know if you have any feedback.

HELPERS

openapi.cors_simple

  $c = $c->openapi->cors_simple($method);

Will validate the incoming request using the $method, if the incoming request HTTP method is

  • The HTTP method is GET, HEAD or POST.

  • The "Content-Type" header is application/x-www-form-urlencoded, multipart/form-data or text/plain.

  • The "Origin" header set

openapi.cors_simple will automatically generate a "400 Bad Request" response if the "Access-Control-Allow-Origin" response header is not set.

The $method can be a simple method name in the current controller, a sub ref or a FQN function name, such as MyApp::validate_simple_cors. See "SYNOPSIS" for example usage.

METHODS

register

Called by Mojolicious::Plugin::OpenAPI.

SEE ALSO

Mojolicious::Plugin::OpenAPI.