26

I am working on express js and I need to redirect to a page which needs authentication. This is my code:

router.get('/ren', function(req, res) {
    var username = 'nik',
        password = 'abc123',
        auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');

    res.redirect('http://localhost:3000/api/oauth2/authorize');
})

How can I set headers to this redirect command?

Dmitry Shvetsov
  • 651
  • 10
  • 19
nikhil.g777
  • 882
  • 3
  • 12
  • 24

5 Answers5

22

Doesn't express forward the headers automatically if you redirect with 301 (Moved Permanently) or 302 (Found)?

If not, this is how you can set headers:

res.set({
  'Authorization': auth
})

or

res.header('Authorization', auth)

and then call the

res.redirect('http://localhost:3000/api/oauth2/authorize');

Finally, something like that should work:

router.get('/ren', function(req, res) {
    var username = 'nik',
        password = 'abc123',
    auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

    res.header('Authorization', auth);

    res.redirect('http://localhost:3000/api/oauth2/authorize');
});
David Zorychta
  • 13,039
  • 6
  • 45
  • 81
Stavros Zavrakas
  • 3,045
  • 1
  • 17
  • 30
  • Thanks, it works and i got a response with status code 302 and body : 'Found. redirecting to http://localhost:3000/api/oauth2/authorize ' but the browser remains on the same page, can you please help – nikhil.g777 Oct 12 '16 at 12:08
  • @user3655266 I need more information. What did you register against the /api/oauth2/authorize route? What do you expect to happen? Render something or return some json data or something else? – Stavros Zavrakas Oct 12 '16 at 12:13
  • In the /api/oauth2/authorize, i have rendered a page using ejs view engine...res.render('dialog') – nikhil.g777 Oct 12 '16 at 12:14
  • and i forgot to mention, the endpoint is at router.post('/ren')......when i use router.get('/ren') and send a GET request, i am getting unathorized – nikhil.g777 Oct 12 '16 at 12:18
  • 34
    as of 2017, setting headers before a redirect doesn't work in node. – Rachelle Uy Jul 07 '17 at 03:17
  • 6
    2018 nothing changed.. setting headers before a redirect doesn't work in node, any workarounds? – raksja Jan 29 '18 at 22:52
  • 9
    2019 nothing changed, and for consistency: any workarounds? – ndtreviv Aug 17 '19 at 21:22
  • 2
    Would have continued the trend with 2021 but I'm too early. I don't think you can change the headers the browser sends to the next request. All redirects (301, 302) are solely browser based. – Paul Stelian May 08 '20 at 08:53
  • 2021 and still the same. Life is kinda sad. – m4heshd Nov 21 '21 at 11:54
  • 2022 nothing changed – Matteo Jan 13 '22 at 16:08
  • 2023..lets go!! – Cozzbie Jan 05 '23 at 16:45
  • 2023 reading this. So there is no solution for this. My express js app with cors middleware always throws frontend error with redirect , reason being the redirect request goes as a get request of the url mentioned and Access-control-origin has *(wildcard) enabled . So it becomes a CORS issue as I already use credentials : true property – Nirmal Kumar Jan 25 '23 at 17:04
3

As people have asked if there was any workaround about the fact headers are not properly set after a redirect, there is actually two ways you can work with:

First, by using a query parameter in the redirect url, which you could be extracted client-side. You could even remove it on load from the url using the history API, like showed here.

history.pushState(null, '', location.href.split('?')[0])

Another solution would be to set a cookie before the redirect, and getting it in the client. Personally I prefer that in the sense it doesn't pollute my url in any way, I just need to remove this cookie on load with a simple helper:

export const removeCookie = name => {
  document.cookie = `${name}=; Max-Age=0`
}
Preview
  • 35,317
  • 10
  • 92
  • 112
2

It is not a Express or any backend limitation, is just the way that browsers works, Express just responds with a Redirect header and the browser implements the redirection, if you are redirecting to the same domain then you got all headers, cookies and the original payload.

But if you are redirecting to another domain, the browser rip off the headers for security reasons and is nothing that you can do about it, so if you really need to do it, you will need to consume the external service with your own service in the backend, nothing with Redirect Header because this depends of the browser implementation.

0

I haven't tried this solution myself, but I think it worth the shot.

res.location(REDIRECT_URL)
res.set(HEADERS)

res.stats(302).end()

I hope it helps, Abel

Abel Osorio
  • 843
  • 8
  • 13
-11

Why cant you try the axios library

    npm install axios

and then

    return new Promise((resolve, reject) => {

        axios({
            "headers" : {
                "content-type" : "application/vnd.api+json"
            },
            "method" : method,
            "url" : url,
            "data" : data
        }).then((ax_res) => {
            var obj = {
                "status" : ax_res.status,
                "data" : ax_res.data
            }
            resolve(obj)
            return(obj)
        }).catch((ax_res) => {
            var obj = {
                "status" : ax_res.response.status,
                "data" : ax_res.response.data
            }
            resolve(obj)
            return(obj)
        })

    })
MJ007
  • 23
  • 1
  • 1
  • 19