Exposing multiple virtual hosts with a single OAuth application
For security reasons it is usually not possible to use multiple virtual hosts with a single OAuth application – the redirect URL has to match exactly what was registered in the OAuth application. This post explains how to expose more than one virtual host with a single OAuth application using Caddy Security.
Caddy Security is a popular plugin for the Caddy Webserver that takes care of authentication and authorization among other things. You can use it with various OAuth IDPs such as Github to protect resources from being publicly accessible.
When registering the OAuth application you are required to provide a callback
URL – this callback URL should point back to your Caddy instance to receive the
credential or code with which it can obtain the Bearer token. If your auth port
al is running on a dedicated domain, such as auth.example.com
but you’re
trying to authenticate for service.example.com
, IDPs will reject the
authentication for security reasons because the redirect URL does not match the
callback URL.
Caddy Security supports doing a redirect on the server side once the authentication flow succeeded. The way it works is that it stores the originating URL for which authentication is required in a Cookie – then, when authentication succeeded, it reads the Cookie that the browser sent along and performs the redirect.
The documentation lists this feature under “Miscellaneous” – it wasn’t obvious to me that this is indeed what I was looking for. Here’s an example on how to use it:
{
security {
authentication portal myportal
authorization policy mypolicy1 {
set auth url https://auth.example.com/login?redirect_url=https://app1.example.com
}
authorization policy mypolicy2 {
set auth url https://auth.example.com/login?redirect_url=https://app2.example.com
}
}
}
auth.example.com {
authenticate with myportal
}
app1.example.com {
authorize with mypolicy
}
app2.example.com {
authorize with mypolicy
}
The important part is to set the redirect_url
parameter in the definition of
the authorization policy. For each virtual host that you want to expose using
the same authentication portal you have to define a separate authorization
policy in order to be able to provide the correct redirect URL.