-4

I am trying to make session using express-session with passport in cross domain .I take help of following links Sending credentials with cross-domain posts? Passport js fails to maintain session in cross-domain

**I am getting below error**

Failed to load http://localhost:5000/users/login: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

here is my whole code https://github.com/naveennsit/Cors

client index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="style/style.css" rel="stylesheet" type="text/css"/>
    <script src="../node_modules/jquery/dist/jquery.js"></script>
    <script src="jquery.js"></script>
</head>
<body>
<script>
    $(function () {
        $.ajax({
            url: 'http://localhost:5000/users/login',
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({id: 5}),
            dataType: 'json',
            xhrFields: {
                withCredentials: true,

            },
            crossDomain: true,
            success: function () {
                console.log('success');
            },
            error: function () {
                console.log('error')
            }
        });
    })
</script>
</body>
</html>

server code server.js

var app = require('./app');
const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
    console.log(`app is running on ${PORT}`);
})

app.js

const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const path = require('path');

const morgan = require('morgan');
const cors = require('cors');
const session = require('express-session');
const passport = require('passport');



const app = express();



// Middleware
app.use(bodyParser.urlencoded({extended: false}));

app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cookieParser());
app.use(cors());

app.use(cookieParser());

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
    res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
    next();
});
app.use(session({
    secret: 'secret',
    resave: false,
    domain: '.localhost:3000',
    saveUninitialized: false,
    cookie:  {
        domain: '.localhost:3000',
        maxAge: 24 * 6 * 60 * 10000
    },
}))



app.use(passport.initialize());
app.use(passport.session());

//Routes


app.use('/users', require('./routes/user.route'))


module.exports = app;

controller.js

const passport = require('passport');


const passportConfig = require('../passport')
module.exports = {
    login: async (req, res, next) => {
        console.log(req.body);
        try {

            req.login(req.body.id, function () {
                res.json({message: "Registration successfully"});

            })
        } catch (e) {
            console.log(e)
        }

    },

}

passport.js

const passport = require('passport');
passport.serializeUser(function(id, done) {
    console.log('ddd');
//    console.log(user);
    done(null, id);
});

passport.deserializeUser(function(id, done) {
    console.log('deserializeUser');
    done(null, id);
    // db.User.findById(id, function (err, user) {
    //     done(err, user);
    // });
});

routes

const express = require('express');
const router = require('express-promise-router')();


const controller = require('../controllers/user.controller');



router.route('/login',)
    .post(controller.login)



module.exports = router;

I want to add session in cross-domain.I already apply cors plugin still getting same error

Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
user944513
  • 12,247
  • 49
  • 168
  • 318

2 Answers2

0

The easiest way is to use the node.js package cors. The simplest usage is:

var cors = require('cors')

var app = express();

app.use(cors());

When using withCredentials: true in ajax, cors need to configure as below.

app.use(cors({origin: 'http://localhost:3000', credentials: true}));
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38
Mahesh Thumar
  • 4,257
  • 5
  • 22
  • 30
  • please remove this answer – user944513 Aug 21 '18 at 06:08
  • Did you configured the origin? – Mahesh Thumar Aug 21 '18 at 06:13
  • didn't work please checkout my code on github .if you have 2 min please let me know where I am doing wrong – user944513 Aug 21 '18 at 06:15
  • You need to add credentials in access control, (see updated answer) and you are setting header manually after using cors (` res.header("Access-Control-Allow-Origin", "*");` that's an issue.! So comment ``` /* app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization"); res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS"); next(); }); */ ``` – Mahesh Thumar Aug 21 '18 at 06:27
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178415/discussion-between-user944513-and-mahesh-thumar). – user944513 Aug 21 '18 at 06:32
0

You are almost there to solve it. You need to send actually allowed host in Access-Control-Allow-Origin header value and not *

If you want to allow for all origins, then you can include req.headers.origin for Access-Control-Allow-Origin header value in your CORS middleware:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", req.headers.origin);
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, authorization");
    res.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS");
    next();
});
Suresh Prajapati
  • 3,991
  • 5
  • 26
  • 38