jhthorsen / mojolicious-plugin-openapi

OpenAPI / Swagger plugin for Mojolicious
54 stars 44 forks source link

CORS not working with OPTIONS request #99

Closed mario-minati closed 5 years ago

mario-minati commented 5 years ago

We are trying to set up an OpenAPI Rest connection to a Mojolicious server from VueJS with Vuex and Vuex ORM with its REST plugin Vuex ORM Axios.

This plugins uses an OPTIONS request with CORS headers set:

Access-Control-Request-Headers: content-type
Access-Control-Request-Method: GET

These headers are currently not processed of _helper_reply_spec which answers any OPTIONS request in lib/Mojolicious/Plugin/OpenAPI.pm, thus all requests from the Vuex ORM mapper fails.

mario-minati commented 5 years ago

We have tried to solve the problem in a more generic way and developed patches that provide a more complex CORS support, which can be configured via a cors config hash, e. g.:

cors => {
    origin => "http://localhost:8080",
    headers => "content-type",
    methods => qw(get post put delete),
    credentials => 1,
}

The CORS plugin is extended to get it's setting from config, which makes the use of _validate_cors sub unnecessary. That means for sure that you cannot set the origin from within the controller.

The main CORS stuff is refactored in a helper class Mojolicious::Plugin::OpenAPI::Helper::Cors. Most of it's logic and some of it's code is taken from Mojolicious::Plugin::SecureCORS. We have tried to follow Mojolicious::Plugin::OpenAPI's style of sending error messages to the user.

There are still missing tests, but we wanted to give an idea how the CORS stuff might could be improved. Mojolicious::Plugin::OpenAPI.pm Diff Mojolicious::Plugin::OpenAPI::Cors.pm Diff Mojolicious::Plugin::OpenAPI::Helper::Cors.pm

mario-minati commented 5 years ago

Some more infos on the history of this issue and a link to the CORS TR can be read at powerman/perl-Mojolicious-Plugin-SecureCORS#4.

jhthorsen commented 5 years ago

I welcome a PR, even if it's incomplete. A PR will help me get a better overview of what changes have been made.

mario-minati commented 5 years ago

I'll prepare a PR.

plk commented 5 years ago

Very interested in this too - using Swagger UI to a M::P::O server currently doesn't work with CORS non-simple preflight requests because of this. The best I can get with the Mojo SecureCORS plugin is to succeed the OPTIONS request but then it just stops ....

jhthorsen commented 5 years ago

I just opened #102. Please review it and continue the discussion there.

jhthorsen commented 5 years ago

@mario-minati: Not sure if you already know, but wanted to share that version 2.11 has full CORS support ...Unless you find bugs, hehe

mario-minati commented 5 years ago

@jhthorsen: Thanks, saw it on metacpan/recent. I'll adapt our custom code in the next days an test it :-) 👍