Putting internal tools behind your own login with ALB authenticate-oidc
PgHero has only basic auth. I put it behind an ALB listener rule that runs authenticate-oidc against our own admin console, so the tool never sees a password. The Terraform, the small OIDC provider and the rule-order traps.
PgHero has no login of its own. You get HTTP basic auth with one shared username and password, and that is it. When we wanted it on a real hostname for the whole team, I didn't want one more shared password floating around in chat. So I put the login in front of it, on the load balancer, using the ALB's authenticate-oidc action. PgHero itself never sees a credential.
I wrote about setting PgHero up earlier (PgHero with Docker and multiple databases). This post is the part that came after: how to put it, and any other internal tool, behind your own login.
What the ALB does for you
An HTTPS listener rule can have two actions in order. First authenticate-oidc, then forward. When a request matches the rule and has no valid session cookie, the ALB sends the browser to your identity provider, takes the code it gets back, swaps it at the token endpoint, calls the userinfo endpoint and then sets its own session cookie. Only after that does it forward to the target group.
The AWS docs list the details. The action works only on HTTPS listeners. The callback is always https://<your host>/oauth2/idpresponse. The session default is 7 days, and you can set it as low as 1 second. The ALB also adds a signed x-amzn-oidc-data header (an ES256 JWT) with the user's claims, if the app behind wants to know who is calling.
PgHero doesn't care who is calling. That is the nice thing here: the tool needs zero changes.
Our identity provider was already there
We already had an internal admin console with its own login, roles and a list of "products" each role can open. Grafana was the first tool hooked to it. Grafana can do generic OAuth by itself, so for Grafana the console only had to be an OAuth provider and Grafana handled the rest inside the tool.
PgHero can't do that. So I made the console a very small OIDC provider for the load balancer. It has three endpoints per tool:
- an authorize page (behind the console's own login),
POST /v1/oidc/<tool>/token,GET /v1/oidc/<tool>/userinfo.
The client here is the ALB, not the tool. Each tool gets its own client id and secret.
The authorize step
The ALB redirects the browser to the console's authorize page with client_id, redirect_uri, state and nonce. If the person isn't signed in to the console, the console's normal login runs first. Then the page posts the request to the backend, which checks four things before it redirects anywhere: the response type is code, the client id is the tool's, the redirect_uri is exactly https://<tool host>/oauth2/idpresponse, and the operator's role has that tool.
That exact match on redirect_uri matters a lot. Without it a crafted link could bounce somebody's code to a foreign site. The code itself is 32 random bytes, stored only as a SHA-256 hash, lives for one minute and can be taken once.
The token step and the HS256 ID token
The ALB posts the code with its client id and secret. We accept the secret both as HTTP Basic and in the form body, compared in constant time. The response has an access token (5 minutes) and an ID token.
The ID token needs one small decision. The ALB takes the user's claims from userinfo, not from the ID token, but it still expects one in the response. Signing it with RS256 would mean a key pair and a JWKS endpoint. OIDC Core section 10.1 lets a confidential client use HS256 with the client secret as the key, so that is what we did:
func Mint(issuer, clientID, secret, email, nonce string, now time.Time) (string, error) {
claims := map[string]any{
"iss": issuer,
"sub": email,
"aud": clientID,
"iat": now.Unix(),
"exp": now.Add(5 * time.Minute).Unix(),
"email": email,
}
if nonce != "" {
claims["nonce"] = nonce
}
head, err := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"})
if err != nil {
return "", err
}
body, err := json.Marshal(claims)
if err != nil {
return "", err
}
enc := base64.RawURLEncoding
signing := enc.EncodeToString(head) + "." + enc.EncodeToString(body)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(signing))
return signing + "." + enc.EncodeToString(mac.Sum(nil)), nil
}
The iss has to be the same string you put in the listener rule's issuer. Trailing slash included, so our code trims it before it signs anything.
Userinfo checks the access token, then looks the operator up again and checks the role still has the tool. Somebody removed in the two minutes between authorize and userinfo is refused there itself.
The listener rule in Terraform
Our first rollout was done with the AWS CLI, and the Terraform came later. Here is the same thing as Terraform, one rule and one target group per tool, checked with terraform validate on Terraform 1.17.1 and AWS provider 6.74.0:
resource "aws_lb_listener_rule" "tool" {
for_each = var.tools
listener_arn = var.https_listener_arn
priority = each.value.priority
condition {
host_header {
values = [each.value.host]
}
}
action {
type = "authenticate-oidc"
order = 1
authenticate_oidc {
issuer = var.idp_url
authorization_endpoint = "${var.idp_url}/${each.key}/authorize"
token_endpoint = "${var.idp_url}/v1/oidc/${each.key}/token"
user_info_endpoint = "${var.idp_url}/v1/oidc/${each.key}/userinfo"
client_id = each.key
client_secret = var.client_secrets[each.key]
scope = "openid email"
session_cookie_name = "AWSELBAuthSessionCookie-${each.key}"
session_timeout = 28800
on_unauthenticated_request = "authenticate"
}
}
action {
type = "forward"
order = 2
target_group_arn = aws_lb_target_group.tool[each.key].arn
}
}
And the input for PgHero:
tools = {
pghero = {
host = "pghero.example.com"
port = 8080
health_path = "/health"
priority = 17
}
}
The client secrets come in as a separate sensitive map, so they never show up in plan output. They will still be in state, so the state bucket needs the same care as the secret.
session_timeout = 28800 is 8 hours. One working day. The 7 day default felt too long for a tool that can show query text from production.
Things that caught me
Rule priority first. Rules are checked from the lowest number up and the first match wins. If you already have a broad rule for *.example.com at priority 10 and add the tool's host rule at 17, the request never reaches the gate. It goes straight to whatever the wildcard forwards to, with no login, and nothing tells you. Put the tool rules above any wildcard, then open the host in a private window and confirm you land on the login page.
One cookie name per tool. The AWS docs say each rule with an authenticate action should have its own cookie name when the apps need independent sign-in. With a shared cookie, a session made for one tool is good for another, and then the per-tool role check in userinfo means very less, since it only runs at sign-in.
Health checks are fine. The target group health check goes from the ALB straight to the task, not through the listener rules, so /health keeps working with no extra rule. An outside uptime checker is different: it comes in through the listener and gets a 302 to the login page. If you want that, add a narrow rule for the exact path at a lower number than the gate.
The ALB must reach the IdP's token and userinfo endpoints over IPv4 with a certificate from a public CA, and the DNS name has to resolve publicly. Ours sits on the same ALB, so that part was free.
Roles live in the console only. Revoking a tool from a role takes effect at the next sign-in, not mid-session. With 8 hour sessions that's the real worst case, and I'm okay with that for a read-only database tool. Is it fine for something that can write? Probably not; I'd go shorter there.
Checking the flow without a browser
curl shows the gate quickly:
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://pghero.example.com/
You should see a 302 with a redirect_url on the console's authorize page and client_id=pghero in the query. A 200 means the gate is not in front, and most of the times that is the priority problem above. After a change to the rule, give it about a minute before you test.
Our PgHero task runs in private subnets (the layout from Building a VPC by hand) with a security group that allows only the ALB. That part matters as much as the rule. A gate on the ALB means nothing if the task can be reached some other way.