如何使用Passport/Facebook策略/对Supertest请求进行身份验证? [英] How to authenticate Supertest requests with Passport /Facebook strategy/?

查看:102
本文介绍了如何使用Passport/Facebook策略/对Supertest请求进行身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Passport.js进行身份验证(Facebook策略),并通过Mocha和Supertest进行测试.如何使用Supertest for Facebook策略创建会话并发出经过身份验证的请求?

I'm using Passport.js for authentication (Facebook strategy) and testing with Mocha and Supertest. How can I create a session and make authenticated requests with Supertest for Facebook strategy?

这是用户未登录时的示例测试:

Here is the example test for when user not logged in:

  describe 'when user not logged in', ->

    describe 'POST /api/posts', ->
      it 'respond with 401', (done)->
        request(app).
          post(API.url('posts')).
          set('Accept', 'application/json').
          send(post: data).
          expect('Content-Type', /json/).
          expect(401, done)

谢谢您的建议:D

推荐答案

这里看起来几乎没有什么不同,所以我将答案分为两部分.

There are few different things here it looks like, so I've divided my answer into two parts.

1)您首先必须通过Facebook创建测试用户.您可以通过以下两种方法之一进行操作:1)Facebook的Graph API,或2)通过应用程序的角色"页面.

1) You first must create test users through the Facebook. You can do so via one of two methods, 1) Facebook's Graph API, or 2) Through the Roles page of your application.

2)使用SuperTest持久化会话的推荐方法是使用称为.agent()的SuperAgent方法来持久化会话.您可以使用SuperAgent进行的任何操作,都可以使用SuperTest进行的操作.有关更多信息,请参见此 Github 帖子.

2) The recommend method for persisting sessions with SuperTest is using a SuperAgent method called .agent() to persist sessions. Anything you can do with SuperAgent, you can do with SuperTest. See this Github post for more.

var supertest = require('supertest');
var app = require('../lib/your_app_location');

describe('when user not logged in', function() {
    describe('POST /api/posts', function() {
        var agent1 = supertest.agent(app);

        agent1
            .post(API.url('posts'))
            .set('Accept', 'application/json')
            .send(post: data)
            .(end(function(err, res) {
                should.not.exist(err);
                res.should.have.status(401);
                should.exist(res.headers['set-cookie']);
                done();
            }));
    });
});

VisionMedia Github上还有其他一些不错的代码段.请在此处找到它们.

There are some other good code snippets on the VisionMedia Github. Please find them here.

这篇关于如何使用Passport/Facebook策略/对Supertest请求进行身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆