Cors_plug config for making some of the endpoints public

Hey there,

I am using cors_plug with a whitelist in my endpoint file, but i would like ot make a subset of endpoints publicly available based on url.
is this possible?

I know that this is not possible, but on idea level this is what I am looking for:

  if x do
    plug(CORSPlug, origin: "hehexd.com")
  else
    plug(CORSPlug, origin: "*")
  end

I tried to move it to the router and have different pipelines, but then i would need to add options request type to all of my non get requests and that is not something i’d like to do

Any ideas?

Make a plug, which checks the request route and only for certain ones applies the cors plug. Mount that one in the endpoint.

and how do i apply the cors plug?

MyPlug.call(conn, opts)

yeah, but i mean inside this plug how do i “call” the cors plug?

Within your plug‘s code you can call the cors plug like I wrote above.

def call(conn, opts) do
  if x do
    CorsPlug.call(conn, opts)
  else
    conn
  end
end
3 Likes

thanks, now just need to figure how to pass the relevant whitelist or the “*”, because i need it in the else path

seems to me that this approach doesn’t want to work with CORSPlug

You could also use pipelines for it in your router, something like:

pipeline :internal do
  plug CORSPlug, origin: "hehexd.com"
end

scope "/" do
  pipe_through [:internal]
  # your internal routes
end

scope "/" do
  # your public routes
end

But if you still need to whitelist cross site requests on public routes, well, then they are not public, and for sure a * pattern would not whitelist anything, since (if that worked) it would match any domain.

if i do this since the cors plug would be in the router I’d need to add options routes to the endpoints where that is applicable

Pipeline plugs are only applied when a route of the router was matched. To handle OPTIONS requests, which are not present in the router, a CORS plug needs to be placed before the router.

You could call the plug with different options in the else case. You might need to look into what init/1 does for your cors plug. Sometimes it changes the format for options, which are later passed to call/2.

yes, in my init i need to call the plugs init