Make a secure oauth API with passport.js and express.js (node.js)

前端 未结 2 1823
悲哀的现实
悲哀的现实 2020-12-12 18:41

I\'ve got I think a specific problem, unless I\'m not doing things in the right way.

I\'ve got an application with 2 sides, a client (html site), and an API (built w

相关标签:
2条回答
  • 2020-12-12 19:06

    Before configuring anything in express app, use the following(exactly the same) to set header of response for cross-domain :

    app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
    if ('OPTIONS' == req.method) {
         res.send(200);
     } else {
         next();
     }
    });
    
    0 讨论(0)
  • 2020-12-12 19:11

    I had the same issue. I was using the Local Strategy on the login page, and then checking to see if the user was on the session on other requests.

    As you say, the solution is to use CORS in order for the session ID to be passed in a cookie using XMLHTTPRequest.

    Instead of using the CORS which does not yet work on all browswers, I deceided to use access tokens on other requests. The workflow I used is as follows:

    POST /login
    
    • Username and password get passed in the body.
    • Authentication using Local Strategy.
    • Response returns the user object, including the access_token

    GET /endpoint/abc123?access_token=abcdefg

    • Token obtained from the login response
    • Authentication using Bearer Strategy (in passport-http-bearer)

    Sessions are now not needed in Express.

    I hope this alternative helps.

    0 讨论(0)
提交回复
热议问题