security – how to configure an NGINX location block to validate bearer token?

I’m advised to have the file uploads handled by the NGINX web server, not by my web app, so I had my self writing this location block which handles file uploads:

location ~ "/upload/([0-9a-zA-Z-.]*)$" {
    ... 
}

my problem is that I can’t leave this configuration as it is without security controls. else my server will be contaminated with unauthorized uploads .

I also have an HTTP bearer token validation server that handles validation requests. for e.g., http://localhost:8080/api/validify with the authorization header 'Authorization': Bearer which will respond by 200 StatusOK with JSON body {"is_valid": true}, else will respond by 401 StatusUnauthorized with JSON body {"error": "Access Token Not Valid"}

I need help rewriting my upload location block with the following logic :

location ~ "/upload/([0-9a-zA-Z-.]*)$" {
    response = send token validation request 
    if ( $(response) != "200") {
        return 401;
    }
    ... 
}

I’ll appreciate providing me guidance/advice of how to send the validation request from an NGINX location block and catch its response code .

I’ll be happier if I’m able to do it as built in solution without extra modules .

Read more here: Source link