Angular 2 doesn't save my Authentication Cookie with CORS

前端 未结 2 785
野的像风
野的像风 2021-01-14 22:41

I have an angular 2 app which should authenticate to a Node Express backend where it sends an login request to the backend and receives a cookie. It should send this cookie

相关标签:
2条回答
  • 2021-01-14 23:30

    I had your situation. With Maciej answer I solved my problem. I added the { withCredentials: true } to my request options that already had the headers.

    Then server-side, on my express base file server.js, i added

    var cors = require("cors");
    var corsSettings = {
      origin: true,
      methods: ['POST'],
      credentials: true
    };
    app.use(cors(corsSettings));
    

    I actually excluded the Access-Control-Allow-Origin:*, so my only header (server-side) is

    app.use(function (req, res, next) {
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, access-control-allow-origin, access-control-allow-headers");
        next();
    });
    

    Just wanna point out that as Maciej mentioned, you need some body in your request. So even if your query doesn't need it you need to call it with an empty body string.

    const jsonHeads = new Headers();
    jsonHeads.append('Content-Type', 'application/x-www-form-urlencoded');
    jsonHeads.append('Access-Control-Allow-Origin', '*');
    jsonHeads.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, access-control-allow-origin');
    options = { headers : myHeaders, withCredentials: true }
    this.http.post('http://myApi:8080/list', '', options);
    

    This way, angular started sending cookies and authenticating properly. I hope this helps. I needed this myself a couple of hours ago.

    0 讨论(0)
  • 2021-01-14 23:32

    By default angular is not sending cookies. Try pass { withCredentials: true } to your RequestOptions:

    let options = new RequestOptions({ headers: headers, withCredentials: true });
    this.http.post(this.connectUrl, <stringified_data> , options);
    
    0 讨论(0)
提交回复
热议问题