簡體   English   中英

使用 angular $http 請求時,passport req.isAuthenticated 總是返回 false

[英]passport req.isAuthenticated always return false when using angular $http request

我正在使用passportjs進行用戶身份驗證。

通過使用postman ,我可以成功登錄並且 req.isAuthenticated 總是在登錄后的子序列請求中返回 true 。

通過使用 angular $http ,但是,登錄可以正常工作,但是 req.isAuthenticated 總是在子序列請求中返回 false。 我的角度應用程序(本地主機:3000)節點應用程序(heroku)在不同的域中。 我的想法是它可能與 CORS 或會話 cookie 相關,因為我在瀏覽器中沒有看到任何 cookie。

我做了什么

  1. 我嘗試將請求標頭設置為允許 CORS。
  2. 我還嘗試在 angular $http 和 node app 上設置Access-Control-Allow-Credentials

不幸的是,所有嘗試都失敗了 T_T

Node.js 設置

    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();
        }
    });

    passport.serializeUser(function(account, done) {
        done(null, account.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        Account.findById(id, function(err, account) {
            done(err, account);
        });
    });

    passport.use('local-signup', new LocalStrategy({
        usernameField: 'email'
    }, function(email, password, done) {
        ....
    }));

    passport.use('local-login', new LocalStrategy({
        usernameField: 'email'
    }, function(email, password, done) {
        ....
    }));

    app.use(morgan('dev')); // log every request to the console

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

    app.use(bodyParser.json());

    app.use(cookieParser(config.app.sessionSecret));

    app.use(session({
        secret: config.app.sessionSecret,
        resave: false,
        saveUninitialized: true,
        cookie: { httpOnly: true, maxAge: 2419200000 }
    }));

    // Passport for account authentication
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions

    ///////////////////////////////////////////////////////////////////route controller function
    authenticate: function(req, res) {
        if (!req.isAuthenticated()) {
            res.redirect('/login');
        } else {
            res.status(200).send('successful');
        }
    }

    $http.post('http://xxxxx/login', 
      {  email: $scope.user.email,
         password: $scope.user.password
      })
    .then(function(response) {
        ...
    }, function(response) {
        ...
    });

    $http.get('http://xxxxx/authenticate',
        { withCredentials: true }).success(function() {
            ...
        })
        .error(function() {
            ... // always get here with 302 redirect
        });

我的問題/我不明白的事情

  1. 是因為瀏覽器中未設置會話 cookie 導致問題嗎
  2. 如果它與 CORS 相關,我是否錯過了任何設置?
  3. 還有什么????

我根據@robertklep 評論自己解決了這個問題。 基本上,passportjs 設置沒有任何問題。 這完全取決於您如何以角度發送 withCredentials 標志。 而不是調用 $http 的 get 或 post 方法。 我使用以下格式,它對我有用

$http({
    method: 'GET',
    url: 'xxxx',
    data: {...},
    withCredentials: true
}).success ....

參考: https : //docs.angularjs.org/api/ng/service/ $http#usage

如果您的登錄服務請求包含“withCredentials”配置選項,如果您提供正確的登錄詳細信息,passport.js 會將憑據附加到請求中。

$http({
method: 'POST',
url: 'http://xxxxx/login',
data: {...},
withCredentials: true})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM