Skip to content

Instantly share code, notes, and snippets.

@bq1990
Created December 17, 2014 15:55
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bq1990/595c615970250e97f3ea to your computer and use it in GitHub Desktop.
Save bq1990/595c615970250e97f3ea to your computer and use it in GitHub Desktop.
Supertest authenticate with bearer token
'use strict';
var should = require('should');
var app = require('../../app');
var request = require('supertest')(app);
describe('GET /api/incidents', function() {
it('should require authorization', function(done) {
request
.get('/api/incidents')
.expect(401)
.end(function(err, res) {
if (err) return done(err);
done();
});
});
var auth = {};
before(loginUser(auth));
it('should respond with JSON array', function(done) {
request
.get('/api/incidents')
.set('Authorization', 'bearer ' + auth.token)
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if (err) return done(err);
res.body.should.be.instanceof(Array);
done();
});
});
});
function loginUser(auth) {
return function(done) {
request
.post('/auth/local')
.send({
email: 'test@test.com',
password: 'test'
})
.expect(200)
.end(onResponse);
function onResponse(err, res) {
auth.token = res.body.token;
return done();
}
};
}
@Gobliins
Copy link

Gobliins commented Feb 9, 2018

i am doing the exact same thing, but onResponse is never called ( I am using supertest 3.0.0 ) and test runner is mocha

@dlhines
Copy link

dlhines commented Sep 3, 2018

Holy crap! Wonderful. Slightly modified but definitely works! Great!

@candy2280
Copy link

Could you please post your modified code?

@itsgratien
Copy link

Thank you. could you please explain why bearer in lowercase not Bearer in uppercase? is a super test only accept bearer in lowercase?

@fhpriamo
Copy link

You can use the auth method instead of setting the Authorization header by hand:

    it('should respond with JSON array', function(done) {
        request
            .get('/api/incidents')
            .auth(auth.token, { type: 'bearer' })
            .expect(200)
            .expect('Content-Type', /json/)
            .end(function(err, res) {
                if (err) return done(err);
                res.body.should.be.instanceof(Array);
                done();
            });
    });
``'

@fhpriamo
Copy link

Thank you. could you please explain why bearer in lowercase not Bearer in uppercase? is a super test only accept bearer in lowercase?

This excerpt from RFC7235 may shed a light on your doubt:

  1. Access Authentication Framework

2.1. Challenge and Response

HTTP provides a simple challenge-response authentication framework
that can be used by a server to challenge a client request and by a
client to provide authentication information. It uses a case-
insensitive
token as a means to identify the authentication scheme,
followed by additional information necessary for achieving
authentication via that scheme.

Note that by "token", the RFC author is referring to a lexical token, representing the authentication scheme (like "Basic", "Bearer", etc...), or "auth-scheme" for short, and not your authentication token string.

The Basic authentication scheme builds on top of the HTTP Authentication Framework, along with the Bearer scheme. Take a look at what the Basic Authentication RFC (RFC767 states in the following section:

The Basic authentication scheme utilizes the Authentication Framework
as follows.

In challenges:

o The scheme name is "Basic".

o The authentication parameter 'realm' is REQUIRED ([RFC7235],
Section 2.2).

o The authentication parameter 'charset' is OPTIONAL (see
Section 2.1).

o No other authentication parameters are defined -- unknown
parameters MUST be ignored by recipients, and new parameters can
only be defined by revising this specification.

See also Section 4.1 of [RFC7235], which discusses the complexity of
parsing challenges properly.

Note that both scheme and parameter names are matched case-
insensitively.

So, although it's common to see auth-schemes written with the first letter capitalized, they are in fact case-insensitive.

@refaelsh
Copy link

refaelsh commented Oct 8, 2021

Thank you very much for this!

@Deevyne99
Copy link

please i have a question ... how do i test a secured route with jest (supertest) ....... where when a user login it generate a jwt and then that jwt generated will be used as a middleware to test other routes?????

@Lefti90
Copy link

Lefti90 commented Jan 17, 2024

You can use the auth method instead of setting the Authorization header by hand:

    it('should respond with JSON array', function(done) {
        request
            .get('/api/incidents')
            .auth(auth.token, { type: 'bearer' })
            .expect(200)
            .expect('Content-Type', /json/)
            .end(function(err, res) {
                if (err) return done(err);
                res.body.should.be.instanceof(Array);
                done();
            });
    });
``'

This worked for me. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment