Skip to content

Instantly share code, notes, and snippets.

@lenisko
Forked from Paturages/conf.d~auth.conf
Created October 11, 2022 02:16
Show Gist options
  • Save lenisko/b9107401182c30a59b31d3f0a825c8ee to your computer and use it in GitHub Desktop.
Save lenisko/b9107401182c30a59b31d3f0a825c8ee to your computer and use it in GitHub Desktop.
Discord OAuth protected endpoints with only nginx
js_include conf.d/oauth2.js;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
location / {
auth_request /_auth_init;
}
location = /_auth_init {
set $access_token "";
internal;
js_content fromCode;
}
location /_auth {
internal;
gunzip on;
proxy_method POST;
proxy_set_header Content-Type "application/x-www-form-urlencoded";
proxy_pass https://discordapp.com/api/oauth2/token;
}
location /_me {
internal;
gunzip on;
proxy_method GET;
proxy_set_header Authorization "Bearer $access_token";
proxy_pass https://discordapp.com/api/users/@me;
}
}
// Discord application credentials
var CLIENT_ID = 'client id';
var CLIENT_SECRET = 'client secret';
// Base URL of the protected routes
var BASE_URL = 'http://localhost';
// A whitelist of Discord user IDs you wanna whitelist
var whitelist = [
'107217872262017024' // Paturages
];
function fromCode(r) {
function me(reply) {
if (reply.status == 200) {
var response = JSON.parse(reply.responseBody);
if (whitelist.indexOf(response.id) > -1) {
r.return(204);
} else {
r.return(403);
}
} else {
r.return(401);
}
}
function auth(reply) {
if (reply.status == 200) {
var response = JSON.parse(reply.responseBody);
// Set the variable for /_me
r.variables.access_token = response.access_token;
r.subrequest('/_me', me);
} else {
r.return(401);
}
}
var code = r.variables.request_uri.split('=')[1];
var path = r.variables.request_uri.split('?')[0];
r.subrequest(
'/_auth',
{
method: 'POST',
body:
'client_id=' + CLIENT_ID +
'&client_secret=' + CLIENT_SECRET +
'&grant_type=authorization_code' +
'&code=' + code +
'&redirect_uri=' + BASE_URL + path +
'&scope=identify'
},
auth
);
}
user nginx;
worker_processes 1;
# Load the dynamic NJS module
load_module modules/ngx_http_js_module.so;
load_module modules/ngx_stream_js_module.so;
events {
worker_connections 1024;
}
http {
include /etc/nginx/conf.d/*.conf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment