Securing Internal Services Behind an OAuth2 Provider with Caddy
Tags: devops, oauth2, proxy, security
Published: 2018-09-17 20:26:13

---
title: Securing Internal Services Behind an OAuth2 Provider with Caddy
published: true
description: Using Caddy and a couple of plugins, we can secure internal services behind an OAuth2 login portal.
tags: devops,oauth2,proxy,security
canonical_url: https://kamal.io/blog/securing-internal-services-behind-oauth2-with-caddy/
---

<small>Last updated on Mar. 1, 2019</small>

In the video below, you can see that `secret.int.localtest.me`&dagger; is secured behind a Google OAuth2 login. Unauthenticated requests are redirected to a login portal, `auth.int.localtest.me`, which asks the user to log in using Google. With this, we are able to authenticate once for all sites under `int.localtest.me`.

{% youtube EMr-eLJdYhE %}

&dagger; `localtest.me` as well as any of its subdomains resolve to `127.0.0.1`. This makes testing local services much easier. This is only relevant to the video demo.

## 🤔 How does this work?

Behind the scenes, authentication is handled using JWT Tokens set as cookies on the `int.localtest.me` hostname, making them available to all subdomains. The JWT token is checked on every request to authenticated URLs. This is handled by the [`http.jwt` plugin](https://caddyserver.com/docs/http.jwt).

The login portal is served using the [`http.loginsrv` plugin](https://caddyserver.com/docs/http.login), which is a Caddy binding to [tarent/loginsrv](https://github.com/tarent/loginsrv).

## 🛠 How do I set this up?

ℹ️ **UPDATE Mar. 1, 2019** Due to Google+ being deprecated, it's no longer necesary to enable its API and OAuth scopes. I've removed the sections relating to that below.

We will assume the following:

* All internal services are hosted on `*.int.domain.tld`
* The login portal will be served on `login.int.domain.tld`
* The OAuth2 provider is Google with a list of approved email addresses
* Caddy is used as the front-facing proxy or webserver for all internal services

### 🔓 Base unsecured environment

We will start with an internal service, publicly accessible:

`Caddyfile`
```
secret.int.domain.tld {
    ...
}
```

### 📸 Install the Caddy plugins

👋🏼 **I prefer to run Caddy inside a Docker container. But, you don't have to!** You can skip this section, but make sure that your Caddy binary has the `http.jwt` and `http.login` plugins compiled. You can either compile the binary yourself or download a pre-built binary from [Caddy's website](https://caddyserver.com/download) making sure to include the plugins I mentioned.




The `abiosoft/caddy` image doesn't include the `http.jwt` and `http.login` plugins, so we will need to build our own image. To do that, run:

```
docker build -t caddy-jwt-login --build-arg plugins="jwt,login" github.com/abiosoft/caddy-docker.git
```

Make sure to include any other plugins you might need if you are hosting other sites on the same Caddy instance. Replace `caddy-jwt-login` with a different tag/image name if it makes sense for you.

This will be the image that we will base our Caddy container on, instead of `abiosoft/caddy`.

🌟 I've built and published an image that you can use, but I can't promise that it will always be up to date! `kamaln7/caddy-jwt-login`. As of right now, the latest version is `kamaln7/caddy-jwt-login:0.11.0`.

### 🔑 Set up the Google OAuth2 provider

In order to be able to use Google as an OAuth2 provider, we'll need to create a project in the Developers Console and add an OAuth2 service to it. Start by creating a new project [here](https://console.developers.google.com/projectcreate).

Then, browse to [the developer console](https://console.developers.google.com/apis/dashboard). Make sure your project is selected in the top-left corner.

Go to [the Credentials page](https://console.developers.google.com/apis/credentials), accessible from the left sidebar. Click on the "Oauth consent screen" tab and fill in "Application name".

Scroll down to "Authorized domains" and enter your top-level domain name in the field (`domain.tld`). Save and return to the Credentials page.

In the Credentials tab, click on the blue Create credentials button and select OAuth client ID.

<div style="text-align:center;"><img alt="screenshot" width="482px" src="https://kmln.sr/cepfXYu"></div>

The Application type will be Web application. Name it whatever you want, and add `https://auth.int.domain.tld/login/google` to the Authorized redirect URIs list. **Don't click Create right after filling out the field.** Click anywhere else on the page to add it to the list and then click Create. Dumb UX, I know. But it's necessary.

<div style="text-align:center;"><img alt="screenshot" width="632px" src="https://kmln.sr/CcTZauP"></div>

On the following page, you will get a popup with your Client ID and secret. Save those somewhere because we will need them later.

### 🌐 Create the login portal

Add the following to your Caddy config. Replace `YOURCLIENTID` with your Client ID and `YOURCLIENTSECRET` with the secret.

```
auth.int.domain.tld {
        tls your@email.address
        redir 302 {
                if {path} is /
                / /login
        }

        login {
                google client_id=YOURCLIENTID,client_secret=YOURCLIENTSECRET
                redirect_check_referer false
                redirect_host_file /redirect_hosts.txt
                cookie_domain int.domain.tld
        }
}
```

This will configure the `http.login` plugin with the Google OAuth2 provider you just created, set the cookies on `int.domain.tld` instead of `auth.int.domain.tld`, and allow rediretion to hosts in the `redirect_hosts.txt` file. More on redirections below.

✅ Now, when you browse to `https://auth.int.domain.tld`, you will be able to log in using your Google account. Note that _anyone_ will be able to log in here, but not everyone will have access to the protected services. We will limit service access to specific email addresses in the following section.

### 🔐 Secure the internal service

All that is left is securing the internal service using the `http.jwt` plugin. We will extract this config into its own snippet so we can easily re-use it with other services.

`Caddyfile`
```
(int-auth) {
        jwt {
                path /
                redirect https://auth.int.domain.tld/login?backTo=https%3A%2F%2F{host}{rewrite_uri_escaped}
                allow sub your@email.address
                allow sub otherpeson@gmail.com
        }
}
```

This will enable JWT auth on `/` (every request) and redirect unauthenticated requests to our login portal. The `backTo` parameter instructs the login portal to redirect back to the internal service on successful login. Repeat the `allow sub ...` directives for each email address you want to allow access.

💭 Remember we talked about a `redirect_hosts.txt` file? This is where it comes in. This file will contain a list of hosts that the login portal is allowed to redirect back to. By default, it won't allow any external URLs outside of `auth.int.domain.tld`. By setting `redirect_check_referer false` and providing a list of approved hosts, we are able to redirect users back to our internal services.

Create a file with each internal service on a line and add it to your Docker image or wherever Caddy is running. Just make sure to update the path to it in the Caddy config above (the `login {}` block).

`redirect_hosts.txt`
```
secret.int.domain.tld
another-service.int.domain.tld
```

✨ Finally, import this snippet in the internal service config:

`Caddyfile`
```
secret.int.domain.tld {
    import int-auth
    ...
}
```

### What now?

That's it! Your internal service(s) are secured using the login portal.

#### OPTIONAL ⚡ Session persistance across Caddy restarts

JWT tokens are signed using a secret. This allows the server to validate that the tokens weren't tampered with (by anyone who doesn't have access to the secret). `http.login` [looks for a secret stored in the `JWT_SECRET` environment variable](https://github.com/tarent/loginsrv/blob/e482109fc416fb8678befb27336ab5d08ff10252/caddy/setup.go#L51-L55):

* if it exists, it uses it
* otherwise, it uses `loginsrv`'s default secret and updates the environment variable. The default secret is a [randomly generated string](https://github.com/tarent/loginsrv/blob/master/login/config.go#L20)

When validating requests, `http.jwt` uses the `JWT_SECRET` environment variable. This is all fine, because the default secret is randomly generated on startup and not a hard-coded string. However, this means that the secret changes when Caddy restarts, which causes all users to be logged out as their tokens become invalidated.

To make sessions persist across restarts, we need to set our own fixed secret. You can generate two random 16-character-long strings [on random.org](https://www.random.org/strings/?num=2&len=16&digits=on&upperalpha=on&loweralpha=on&unique=on&format=html&rnd=new) and put them together as a 32-character-long secret. (You need a paid random.org account to generate strings longer than 20 characters). Set the `JWT_SECRET` environment variable to this token and make it available to Caddy.

# 📚 Resources

* [tarent/loginsrv](https://github.com/tarent/loginsrv)
* [http.login](https://caddyserver.com/docs/http.login) - Caddy plugin
* [http.jwt](https://caddyserver.com/docs/http.jwt) - Caddy plugin
* [loginsrv &larr; OAuth2](https://github.com/tarent/loginsrv#oauth2)

---

I hope you all found this useful! I personally _love_ Caddy and I'm always looking for new cool ways to use it. I'm always happy to hear any kind of feedback in the comments 😄

_This post was originally published on [kamal.io](https://kamal.io/blog/securing-internal-services-behind-oauth2-with-caddy/)._