Securing your code server is critical, especially in collaborative environments. This tutorial will guide you through configuring Nginx as a reverse proxy for your code server, using OAuth2 Proxy for authentication, and Keycloak as the identity provider.
Prerequisites
- A Linux server with Nginx installed.
- OAuth2 Proxy installed on your server.
- A running Keycloak instance.
- Root or sudo access to the server.
Step 1: Set Up Keycloak
Keycloak serves as the identity provider in this setup.
- Log in to the Keycloak admin console.
- Create a new realm for your project.
- Under the Clients tab, create a new client:
- Client ID:
oauth2-proxy
- Client Protocol:
openid-connect
- Access Type:
confidential
- Client ID:
- In the client settings, set the Redirect URI to
https://your-server-domain/oauth2/callback
. - Note the client ID, client secret, and Keycloak’s
Authorization Endpoint
andToken Endpoint
.
Step 2: Configure OAuth2 Proxy
OAuth2 Proxy acts as the middleware between Keycloak and Nginx.
- Create a configuration file for OAuth2 Proxy:
# /etc/oauth2-proxy/oauth2-proxy.cfg
client_id=your-keycloak-client-id
client_secret=your-keycloak-client-secret
provider=oidc
oidc_issuer_url=https://your-keycloak-domain/realms/your-realm
redirect_url=https://your-server-domain/oauth2/callback
cookie_secret=your-random-cookie-secret
upstreams=http://localhost:8080- Start OAuth2 Proxy as a service or container.
Step 3: Configure Nginx
Nginx acts as the reverse proxy and integrates with OAuth2 Proxy.
# /etc/nginx/sites-available/code-server
server {
listen 80;
server_name your-server-domain;
location /oauth2/ {
proxy_pass http://localhost:4180;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
auth_request /oauth2/auth;
error_page 401 = /oauth2/sign_in;
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
- Enable the configuration and restart Nginx:
sudo ln -s /etc/nginx/sites-available/code-server /etc/nginx/sites-enabled/
sudo systemctl restart nginx
Step 4: Verify the Setup
Access your code server through the configured domain. OAuth2 Proxy will redirect you to Keycloak for authentication. Once authenticated, you’ll be redirected back to the code server.
Conclusion
This setup ensures your code server is secure and integrates seamlessly with OAuth2 Proxy and Keycloak. By using Nginx as a reverse proxy, you add an additional layer of flexibility and security to your deployment.