I am using njs ngx_http_auth_request_module.
I have js function like this;
function introspectAccessToken(r) {
r.subrequest("/_oauth2_send_request",
function(reply) {
if (reply.status == 200) {
r.return(204); // Token is valid, return success code
} else {
// need 302 here
}
}
);
}
The documentation says "If the subrequest returns a 2xx response code, the access is allowed. If it returns 401 or 403, the access is denied with the corresponding error code. Any other response code returned by the subrequest is considered an error." http://nginx.org/en/docs/http/ngx_http_auth_request_module.html
I need to return 302 to user if subsequest enters "else" block.
Is there anyway to achieve this? If I set r.return(302), it shows Error page in browser as documentation said.
edit: my nginx.conf
location /my-webclient {
auth_request /_oauth2_token_introspection;
root /usr/share/nginx/html;
rewrite ^ /hmb-profile-webclient/index.html break;
}
location = /_oauth2_token_introspection {
internal;
js_content introspectAccessToken;
}
location /_oauth2_send_request {
internal;
proxy_method POST;
proxy_set_body $cookie_jwt;
proxy_pass http://my-specific-url;
}
http://my-specific-url returns
- 200, if jwt cookie is valid
- 302 (with return location), if jwt cookie is invalid
Got it - I don't think you even need
njs
to do this. In case your token introspection endpoint is NOT build with NJS and its not validating the if the token is a valid json but it is implemented with some other language this NGINX config will work.In case you want to build more logic with NJS like validate the token structure your approach was the right one using NJS with js_set.
njs function
The
error_page
directive will work likewise. Based on you code I assume you already checked out this article?https://www.nginx.com/blog/validating-oauth-2-0-access-tokens-nginx/
ICYMI it's a great blog post about this use case.