Nginx: Is it possible to get response retuned from auth_request - authentication

I am using auth module for nginx. (http://nginx.org/en/docs/http/ngx_http_auth_request_module.html)
Is it possible somehow to store the response from the /auth, so I can send it as a request body to another endpoint.
location /private/ {
auth_request /auth;
proxy_pass ...
proxy_set_body 'Here I want to put /auth response. How?';
}
location = /auth {
proxy_pass ...
}

Short answer:
No, you can't.
Long answer:
You can't get body of a response returned to auth_request. You can get a header returned in the response though, using the auth_request_set directive:
location / {
auth_request /auth;
auth_request_set $auth_foo $upstream_http_foo;
proxy_pass ...
proxy_set_body $auth_foo;
}
The above configuration will set the $auth_foo variable to the value of Foo header of an auth subrequest.

Related

Express - Finding subdomain(s)

I have an Express API that's being called from a VueJS app. The app is located at a domain similar to dev.example.com. Part of my API call checks for subdomains using the built in req.subdomains. In this case it should return an array containing "dev", however, it's returning an empty array. Both the VueJS app and Express API are running on an AWS EC2 instance.
EC2 Nginx File
server {
listen 80 default_server;
server_name _;
#Vue App & Frontend Files
location / {
root /var/www/frontend-app/dist;
try_files $uri /index.html;
}
#Node API Reverse Proxy
location /api/ {
proxy_pass http://localhost:3000/;
proxy_set_header Host $host; //Fix: Passes down the requesting host information
}
}
Frontend API Call
submit() {
axios.post('/api/users/login', {
email:'test#example.com',
password: 'password'
})
}
Express API Sample Route
router.post('/users/login', async(req, res) => {
*Login code omitted*
res.send(req.subdomains); //Returns [], expected result ['dev']
})
I haven't been able to find any solution and was hoping someone would have an idea. Thanks!

NGINX make directory readonly unless authentication provided

I have a directory public, where I will upload various files. I want those files to be downloadable without any authentication.
However, I also want to be able to edit and add new files using WebDAV, if authentication is provided. Is there any way I can have both behaviors on the same directory (location)?
I tried the following hack:
location /public/ {
if ($remote_user != "") {
return 302 e;
}
auth_basic off;
fancyindex off;
dav_methods off;
}
location /public/e {
}
However, I could not find a way to make /public/e index /public/ instead.
I also tried the following:
location /public/ {
if ($remote_user = "") {
auth_basic off;
fancyindex off;
dav_methods off;
}
}
But Nginx complained that I cannot have those directives in an if-statement.
I also tried:
location /public/ {
set $authenticated off;
if ($remote_user != "") {
set $authenticated on;
}
auth_basic $authenticated;
fancyindex $authenticated;
dav_methods $authenticated;
}
But Nginx said a variable is invalid, on or off was expected.
I also thought about making two directories, public and public-webdav, which are symlinked to the same directory, and assign different nginx locations to them, but I was hoping for a cleaner solution.
Thanks!
I solved it using this method:
location #public {
auth_basic off;
}
location /public/ {
if ($remote_user = "") {
error_page 418 = #public;
return 418;
}
}
That is, creating a custom handler for error 418 (teapot) and forcing that error.

Magento 2 API with Angular 2 Token authentication

This is integration issue. Your help is much appreciated (Hint || Guide)
I have both Angular2 and Magento2 (bitnami) installed locally. Magento conf was changed to have the right headers (See below) for CROS.
I'm calling Magento2 from Angular2 to get the token and I'm getting the following issue:
OPTIONS http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token 400 (Bad Request)
XMLHttpRequest cannot load http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token. Response for preflight has invalid HTTP status code 400
EXCEPTION: Response with status: 0 for URL: null
Angular 2 side:
let headers = new Headers({'Content-type': 'application/json'});
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE');
headers.append('Access-Control-Allow-Headers', 'Origin,Authorization,X-Auth-Token,Accept,Content-Type');
headers.append('Access-Control-Allow-Credentials', 'true');
let options = new RequestOptions({ headers: headers });
return this.http.post( 'http://192.168.56.1:82/magento/index.php/rest/V1/integration/admin/token',
JSON.stringify('{"username":"angUser", "password":"angUser2017"}'),
options)
.map(res => res.json());
Magento2 API User
angUser / angUser2017
Consumer Key: 5bhvi7gjvyafcp35rajuxh0y4me2plga
Consumer secret: yh1nefyw1u80rd0ip1q6f8pijv9x72f1
Access Token: g5plfwth2rhlwtuwfhhqp7mg6sebrxc3
Access Token Secret: i1f4t7j65oo8ydtnteub9xr7wrswe99c
Magento headers:
Response Headers
Access-Control-Allow-Credentials: True
Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization
Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin: *
I had a similar issue before and I tracked it down to this method where there is no check for ->isOptions(). So every API call from another domain was triggering a Request method is invalid exception.
/**
* Retrieve current HTTP method.
*
* #return string
* #throws \Magento\Framework\Exception\InputException
*/
public function getHttpMethod()
{
if (!$this->isGet() && !$this->isPost() && !$this->isPut() && !$this->isDelete()) {
throw new \Magento\Framework\Exception\InputException(new Phrase('Request method is invalid.'));
}
return $this->getMethod();
}
You can find a possible workaround in the github forum if you are using apache.
In my specific case what I ended up doing was serving both front-end and api from the same domain to avoid problems with CORS (I use nginx).
An example of the configuration needed for this can be something like:
location ~ ^/(index.php/)?rest {
try_files $uri $uri/ /index.php?$args;
}
location / {
root /var/www/angular/public/;
index index.html;
}

How to serve two web applications behind an nginx reverse proxy

I have two web applications (node.js express apps), web1 and web2. These web apps expect to be hosted on sites that are typically something like http://www.web1.com and http://www.web2.com. I'd like to host them behind an nginx reverse proxy as https://www.example.com/web1 and https://www.example.com/web2. I do not want to expose the two web apps as two subdomains on example.com.
Here is a snippet of my nginx configuration (without SSL termination details) that I had hoped would accomplish this:
server {
listen 443;
server_name .example.com;
location /web1 {
proxy_pass http://www.web1.com:80;
}
location /web2 {
proxy_pass http://www.web2.com:80;
}
}
This works, except for the relative links that the web apps use. So web app web1 will have a relative link like /js/script.js which won't be handled correctly.
What is the best/standard way to accomplish this?
You should be able to do this by checking the $http_referer, something like:
location / {
if ($http_referer ~ ^http://(www.)?example.com/web1) {
proxy_pass http://www.web1.com:80;
}
if ($http_referer ~ ^http://(www.)?example.com/web2) {
proxy_pass http://www.web2.com:80;
}
}
The browser would be setting the referer to http://example.com/web1/some/page when it requests /js/script.js so the apps shouldn't need to change, unless they need to process or care about the referer internally.
The $http_referer does not seem to be easy to find in nginx docs, but is mentioned in a few sites:
http://nginx.2469901.n2.nabble.com/HTTP-Referer-Module-td3356604.html
https://stackoverflow.com/a/18917016/1422492
I think something like this:
server {
listen 443;
server_name .example.com;
location /web1 {
proxy_pass http://www.web1.com:80;
}
location /web2 {
proxy_pass http://www.web2.com:80;
}
location / {
if ($http_referer ~* (/web1) ) {
proxy_pass http://www.web1.com:80;
}
if ($http_referer ~* (/web2) ) {
proxy_pass http://www.web2.com:80;
}
}
How about using cookie and ngx_http_map_module?
Add add_header Set-Cookie "site=web1;Path=/;Domain=.example.com;"; to location /web1 {...} (web2 too).
Add map to under http
map $cookie_site $site {
default http://www.web1.com:80;
"web2" http://www.web2.com:80;
}
Default location is this
location / {
proxy_pass $site;
}
You can pass the value of cookie to proxy_pass directly. But, using map is more secure way.

Nginx config: how to use auth_basic authentication if ssl_client_certificate none provided?

I'm trying to set up Nginx server as follows:
First, the server should check whether the user provides the client SSL certificate (via ssl_client_certificate).
If the SSL certificate is provided, then give access to the site,
If the SSL certificate is NOT provided, then ask the user to enter a password and logs through auth_basic.
I was able to configure both the authentication method at the same time. But this config is superfluous.
To make check, whether the user provides its SSL certificate I try the config like this:
18: if ($ssl_client_verify != SUCCESS) {
19: auth_basic "Please login";
20: auth_basic_user_file .passfile;
21: }
But Nginx returns an error:
"auth_basic" directive is not allowed here in .../ssl.conf:19
How can I to set the condition in this case?
You can set auth_basic configuration in the if clause like this:
server {
listen 443;
auth_basic_user_file .htpasswd;
ssl_client_certificate ca.cert;
ssl_verify_client optional;
...
location / {
...
if ($ssl_client_verify = SUCCESS) {
set $auth_basic off;
}
if ($ssl_client_verify != SUCCESS) {
set $auth_basic Restricted;
}
auth_basic $auth_basic;
}
}
Now, authentication falls back to HTTP Basic if no client certificate has been provided (or if validation failed).
I'm unable to test this currently, but would something like this work?
server {
listen 80;
server_name www.example.com example.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
server {
listen 443;
...
if ($ssl_client_verify != SUCCESS) {
rewrite ^ http://auth.example.com/ permanent;
}
location / {
...
}
}
server {
listen 80;
server_name auth.example.com;
location / {
auth_basic "Please login";
auth_basic_user_file .passfile;
}
}
So basically:
- Accept all initial request (on port 80 for whatever name you're using) and rewrite to ssl
- Check if there's an the client is verified.
- If not, rewrite to an alternate domain that uses basic auth
Like I said, I can't test it right now, but I'll try to get around to it! Let me know if it helps, I'm interested to see if it works.
You may try using a map.
map $ssl_client_verify $var_auth_basic {
default off;
SUCCESS "Please login";
}
server {
....
auth_basic $var_auth_basic;
auth_basic_user_file .passfile;
that way the value depends on $ssl_client_verify but is alsa always defined and auth_basic and auth_basic_user_file is always inside server { block.
Nginx provides no way to fall back to basic authentication when client cert fails. As an alternative you can use variables to restrict access:
location / {
if ($ssl_client_verify = "SUCCESS") {
set $authorized 1;
}
if ($authorized != 1) {
error_page 401 #basicauth;
return 401;
}
}
location #basicauth {
auth_basic "Please login";
auth_basic_user_file .passfile;
set $authorized 1;
rewrite /(.*) /$1;
}
*keep in mind that IfIsEvil and these rules may work incorrectly or interfere with other parts of a larger configuration.
Forget about it, it won't work.
The reason why it fails is because if is not part of the general configuration module as one should believe. if is part of the rewrite module and auth_basic is another module. You just cannot have dynamic vhosts with basic auth.
On the other hand...
You can have dynamic vhosts with their own error pages. The following example is designed for a custom 404 page but you can implement it into your code.
server {
listen 80;
server_name _;
set $site_root /data/www/$host;
location / {
root $site_root;
}
error_page 404 =404 /404.html;
location /404.html {
root $site_root/error_files;
internal;
error_page 404 =404 #fallback_404;
}
location #fallback_404 {
root /var/www/;
try_files /404.html =404;
internal;
}
error_log /var/log/nginx/error.log info;
access_log /var/log/nginx/access.log;
}
What happens...
you are telling Nginx to use /404.html in case of HTTP_NOT_FOUND.
changing the location root to match the Web site error_pages directory.
internal redirection
returning a 404 http code
configure the fallback 404 page in location #fallback_404: In this location, the root is changed to /var/www/ so it will read files from that path instead of $site_root
at the last stage the code returns /var/www/404.html if it exists with a 404 http code.
NOTE: According to Nginx documentation :
Specifies that a given location can only be used for internal
requests. For external requests, the client error 404 (Not Found) is
returned. Internal requests are the following:
requests redirected by the error_page, index, random_index, and try_files directives;
requests redirected by the “X-Accel-Redirect” response header field from an upstream server;
subrequests formed by the “include virtual” command of the ngx_http_ssi_module module and by the ngx_http_addition_module module
directives;
requests changed by the rewrite directive.
Also:
There is a limit of 10 internal redirects per request to prevent
request processing cycles that can occur in incorrect configurations.
If this limit is reached, the error 500 (Internal Server Error) is
returned. In such cases, the “rewrite or internal redirection cycle”
message can be seen in the error log.
Check this link for more, hope that helps.