express server läuft jetzt mit https
This commit is contained in:
Lukas Nowy
2018-12-16 19:08:08 +01:00
parent 5589b0df3f
commit fd947bd852
475 changed files with 91128 additions and 0 deletions

View File

@ -0,0 +1,37 @@
# Javascript Node CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
- image: circleci/node:7.10
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/mongo:3.4.4
working_directory: ~/repo
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
- run: npm install
- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}
# run tests!
- run: npm test

View File

@ -0,0 +1,205 @@
# express-basic-auth
[![npm version](https://badge.fury.io/js/express-basic-auth.svg)](https://badge.fury.io/js/express-basic-auth)
[![npm](https://img.shields.io/npm/dm/express-basic-auth.svg)]()
[![CircleCI](https://circleci.com/gh/LionC/express-basic-auth/tree/master.svg?style=shield&circle-token=74f7b1557100b45259e67d2492c263e4f99365d4)](https://circleci.com/gh/LionC/express-basic-auth/tree/master)
[![David](https://img.shields.io/david/strongloop/express.svg)]()
![TypeScript compatible](https://img.shields.io/badge/typescript-compatible-brightgreen.svg)
[![MIT Licence](https://badges.frapsoft.com/os/mit/mit.svg?v=103)](https://opensource.org/licenses/mit-license.php)
Simple plug & play HTTP basic auth middleware for Express.
## How to install
Just run
```shell
npm install express-basic-auth
```
## How to use
The module will export a function, that you can call with an options object to
get the middleware:
```js
const app = require('express')()
const basicAuth = require('express-basic-auth')
app.use(basicAuth({
users: { 'admin': 'supersecret' }
}))
```
The middleware will now check incoming requests to match the credentials
`admin:supersecret`.
The middleware will check incoming requests for a basic auth (`Authorization`)
header, parse it and check if the credentials are legit. If there are any
credentials, an `auth` property will be added to the request, containing
an object with `user` and `password` properties, filled with the credentials,
no matter if they are legit or not.
**If a request is found to not be authorized**, it will respond with HTTP 401
and a configurable body (default empty).
### Static Users
If you simply want to check basic auth against one or multiple static credentials,
you can pass those credentials in the `users` option:
```js
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl',
}
}))
```
The middleware will check incoming requests to have a basic auth header matching
one of the three passed credentials.
### Custom authorization
Alternatively, you can pass your own `authorizer` function, to check the credentials
however you want. It will be called with a username and password and is expected to
return `true` or `false` to indicate that the credentials were approved or not:
```js
app.use(basicAuth( { authorizer: myAuthorizer } ))
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
```
This will authorize all requests with credentials where the username begins with
`'A'` and the password begins with `'secret'`. In an actual application you would
likely look up some data instead ;-)
### Custom Async Authorization
Note that the `authorizer` function above is expected to be synchronous. This is
the default behavior, you can pass `authorizeAsync: true` in the options object to indicate
that your authorizer is asynchronous. In this case it will be passed a callback
as the third parameter, which is expected to be called by standard node convention
with an error and a boolean to indicate if the credentials have been approved or not.
Let's look at the same authorizer again, but this time asynchronous:
```js
app.use(basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true,
}))
function myAsyncAuthorizer(username, password, cb) {
if (username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
```
### Unauthorized Response Body
Per default, the response body for unauthorized responses will be empty. It can
be configured using the `unauthorizedResponse` option. You can either pass a
static response or a function that gets passed the express request object and is
expected to return the response body. If the response body is a string, it will
be used as-is, otherwise it will be sent as JSON:
```js
app.use(basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
}))
function getUnauthorizedResponse(req) {
return req.auth
? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected')
: 'No credentials provided'
}
```
### Challenge
Per default the middleware will not add a `WWW-Authenticate` challenge header to
responses of unauthorized requests. You can enable that by adding `challenge: true`
to the options object. This will cause most browsers to show a popup to enter
credentials on unauthorized responses. You can set the realm (the realm
identifies the system to authenticate against and can be used by clients to save
credentials) of the challenge by passing a static string or a function that gets
passed the request object and is expected to return the challenge:
```js
app.use(basicAuth({
users: { 'someuser': 'somepassword' },
challenge: true,
realm: 'Imb4T3st4pp',
}))
```
## Try it
The repository contains an `example.js` that you can run to play around and try
the middleware. To use it just put it somewhere (or leave it where it is), run
```shell
npm install express express-basic-auth
node example.js
```
This will start a small express server listening at port 8080. Just look at the file,
try out the requests and play around with the options.
## TypeScript usage
A declaration file is bundled with the library. You don't have to install a `@types/` package.
```typescript
import * as basicAuth from 'express-basic-auth'
```
:bulb: **Using `req.auth`**
express-basic-auth sets `req.auth` to an object containing the authorized credentials like `{ user: 'admin', password: 'supersecret' }`.
In order to use that `req.auth` property in TypeScript without an unknown property error, use covariance to downcast the request type:
```typescript
app.use(basicAuth(options), (req: basicAuth.IBasicAuthedRequest, res, next) => {
res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`)
next()
})
```
:bulb: **A note about type inference on synchronous authorizers**
Due to some TypeScript's type-system limitation, the arguments' type of the synchronous authorizers are not inferred.
For example, on an asynchronous authorizer, the three arguments are correctly inferred:
```typescript
basicAuth({
authorizeAsync: true,
authorizer: (user, password, authorize) => authorize(null, password == 'secret'),
})
```
However, on a synchronous authorizer, you'll have to type the arguments yourself:
```typescript
basicAuth({
authorizer: (user: string, password: string) => (password == 'secret')
})
```
## Tests
The cases in the `example.js` are also used for automated testing. So if you want
to contribute or just make sure that the package still works, simply run:
```shell
npm test
```

View File

@ -0,0 +1,132 @@
const express = require('express')
var app = express()
const basicAuth = require('./index.js')
/**
* express-basic-auth
*
* Example server. Just run in the same folder:
*
* npm install express express-basic-auth
*
* and then run this file with node ('node example.js')
*
* You can send GET requests to localhost:8080/async , /custom, /challenge or /static
* and see how it refuses or accepts your request matching the basic auth settings.
*/
//TODO: Implement some form of automatic testing against the example server
//Requires basic auth with username 'Admin' and password 'secret1234'
var staticUserAuth = basicAuth({
users: {
'Admin': 'secret1234'
},
challenge: false
})
//Uses a custom (synchronous) authorizer function
var customAuthorizerAuth = basicAuth({
authorizer: myAuthorizer
})
//Same, but sends a basic auth challenge header when authorization fails
var challengeAuth = basicAuth({
authorizer: myAuthorizer,
challenge: true
})
//Uses a custom asynchronous authorizer function
var asyncAuth = basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true
})
//Uses a custom response body function
var customBodyAuth = basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
})
//Uses a static response body
var staticBodyAuth = basicAuth({
unauthorizedResponse: 'Haaaaaha'
})
//Uses a JSON response body
var jsonBodyAuth = basicAuth({
unauthorizedResponse: { foo: 'bar' }
})
//Uses a custom realm
var realmAuth = basicAuth({
challenge: true,
realm: 'test'
})
//Uses a custom realm function
var realmFunctionAuth = basicAuth({
challenge: true,
realm: function (req) {
return 'bla'
}
})
app.get('/static', staticUserAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custom', customAuthorizerAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/challenge', challengeAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/async', asyncAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custombody', customBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/staticbody', staticBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/jsonbody', jsonBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realm', realmAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realmfunction', realmFunctionAuth, function(req, res) {
res.status(200).send('You passed')
})
app.listen(8080, function() {
console.log("Listening!")
})
//Custom authorizer checking if the username starts with 'A' and the password with 'secret'
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
//Same but asynchronous
function myAsyncAuthorizer(username, password, cb) {
if(username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
function getUnauthorizedResponse(req) {
return req.auth ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') : 'No credentials provided'
}

View File

@ -0,0 +1,137 @@
/// <reference types="express" />
import { Request, RequestHandler } from 'express'
/**
* This is the middleware builder.
*
* Example:
* const users = { alice: '1234', bob: 'correcthorsebatterystaple' }
* app.use(basicAuth({ users, challenge: true }), myHandler)
*
* @param options The middleware's options (at least 'users' or 'authorizer' are mandatory).
*/
declare function expressBasicAuth(options: expressBasicAuth.BasicAuthMiddlewareOptions): RequestHandler
declare namespace expressBasicAuth {
/**
* The configuration you pass to the middleware can take three forms, either:
* - A map of static users ({ bob: 'pa$$w0rd', ... }) ;
* - An authorizer function
* - An asynchronous authorizer function
*/
export type BasicAuthMiddlewareOptions = IUsersOptions | (IAuthorizerOptions | IAsyncAuthorizerOptions)
/**
* express-basic-auth patches the request object to set an `auth` property that lets you retrieve the authed user.
*
* Example (TypeScript):
* app.use(basicAuth({ ... }), (req: basicAuth.IBasicAuthedRequest, res, next) => {
* res.end(`Welcome ${req.auth.user} (your password is ${req.auth.password})`)
* next()
* })
*/
export interface IBasicAuthedRequest extends Request {
auth: { user: string, password: string }
}
type Authorizer = (username: string, password: string) => boolean
type AsyncAuthorizerCallback = (err: any, authed?: boolean) => void
type AsyncAuthorizer = (username: string, password: string, callback: AsyncAuthorizerCallback) => void
type ValueOrFunction<T> = T | ((req: IBasicAuthedRequest) => T)
interface IBaseOptions {
/**
* Per default the middleware will not add a WWW-Authenticate challenge header to responses of unauthorized requests.
* You can enable that by setting this to true, causing most browsers to show a popup to enter credentials
* on unauthorized responses.
*
* @default false
*/
challenge?: boolean
/**
* You can set the realm (the realm identifies the system to authenticate against and can be used by clients to
* save credentials) of the challenge by passing a string or a function that gets passed the request and is
* expected to return the realm.
*
* @default undefined
*/
realm?: ValueOrFunction<string>
/**
* Per default, the response body for unauthorized responses will be empty.
* It can be configured using the unauthorizedResponse option. You can either pass a static response or a
* function that gets passed the express request object and is expected to return the response body.
* If the response body is a string, it will be used as-is, otherwise it will be sent as JSON.
*
* @default ''
*/
unauthorizedResponse?: ValueOrFunction<any>
}
interface IUsersOptions extends IBaseOptions {
/**
* If you simply want to check basic auth against one or multiple static credentials, you can pass those
* credentials in the users option.
*
* Example:
* const users = { alice: '1234', bob: 'correcthorsebatterystaple' }
* app.use(basicAuth({ users, challenge: true }), myHandler)
*/
users: { [username: string]: string }
}
interface IAuthorizerOptions extends IBaseOptions {
/**
* Set to true if your authorizer is asynchronous.
*/
authorizeAsync?: false
/**
* You can pass your own authorizer function, to check the credentials however you want.
* It will be called with a username and password and is expected to return true or false to indicate that the
* credentials were approved or not:
*
* Example:
* app.use(basicAuth({ authorizer }))
*
* function myAuthorizer(username: string, password: string) {
* return username.startsWith('A') && password.startsWith('secret');
* }
*
* This will authorize all requests with credentials where the username begins with 'A' and the password begins
* with 'secret'. In an actual application you would likely look up some data instead ;-)
*/
authorizer: Authorizer
}
interface IAsyncAuthorizerOptions extends IBaseOptions {
/**
* Set it to true to use a asynchronous authorizer.
*/
authorizeAsync: true
/**
* You can pass an asynchronous authorizer. It will be passed a callback as the third parameter, which is
* expected to be called by standard node convention with an error and a boolean to indicate if the credentials
* have been approved or not.
*
* Example:
* app.use(basicAuth({ authorizer, authorizeAsync: true }));
*
* function authorizer(username, password, authorize) {
* if(username.startsWith('A') && password.startsWith('secret'))
* return authorize(null, true)
*
* return authorize(null, false)
* }
*/
authorizer: AsyncAuthorizer
}
}
export = expressBasicAuth

View File

@ -0,0 +1,82 @@
const auth = require('basic-auth')
const assert = require('assert')
function ensureFunction(option, defaultValue) {
if(option == undefined)
return function() { return defaultValue }
if(typeof option != 'function')
return function() { return option }
return option
}
function buildMiddleware(options) {
var challenge = options.challenge != undefined ? !!options.challenge : false
var users = options.users || {}
var authorizer = options.authorizer || staticUsersAuthorizer
var isAsync = options.authorizeAsync != undefined ? !!options.authorizeAsync : false
var getResponseBody = ensureFunction(options.unauthorizedResponse, '')
var realm = ensureFunction(options.realm)
assert(typeof users == 'object', 'Expected an object for the basic auth users, found ' + typeof users + ' instead')
assert(typeof authorizer == 'function', 'Expected a function for the basic auth authorizer, found ' + typeof authorizer + ' instead')
function staticUsersAuthorizer(username, password) {
for(var i in users)
if(username == i && password == users[i])
return true
return false
}
return function authMiddleware(req, res, next) {
var authentication = auth(req)
if(!authentication)
return unauthorized()
req.auth = {
user: authentication.name,
password: authentication.pass
}
if(isAsync)
return authorizer(authentication.name, authentication.pass, authorizerCallback)
else if(!authorizer(authentication.name, authentication.pass))
return unauthorized()
return next()
function unauthorized() {
if(challenge) {
var challengeString = 'Basic'
var realmName = realm(req)
if(realmName)
challengeString += ' realm="' + realmName + '"'
res.set('WWW-Authenticate', challengeString)
}
//TODO: Allow response body to be JSON (maybe autodetect?)
const response = getResponseBody(req)
if(typeof response == 'string')
return res.status(401).send(response)
return res.status(401).json(response)
}
function authorizerCallback(err, approved) {
assert.ifError(err)
if(approved)
return next()
return unauthorized()
}
}
}
module.exports = buildMiddleware

View File

@ -0,0 +1,100 @@
{
"_args": [
[
"express-basic-auth@^1.1.5",
"/nodeapps/https-test/greenlock-express.js"
]
],
"_from": "express-basic-auth@>=1.1.5 <2.0.0",
"_hasShrinkwrap": false,
"_id": "express-basic-auth@1.1.6",
"_inCache": true,
"_installable": true,
"_location": "/express-basic-auth",
"_nodeVersion": "10.9.0",
"_npmOperationalInternal": {
"host": "s3://npm-registry-packages",
"tmp": "tmp/express-basic-auth_1.1.6_1540564508533_0.23608186033217282"
},
"_npmUser": {
"email": "me@lionc.de",
"name": "lionc"
},
"_npmVersion": "6.4.0",
"_phantomChildren": {},
"_requested": {
"name": "express-basic-auth",
"raw": "express-basic-auth@^1.1.5",
"rawSpec": "^1.1.5",
"scope": null,
"spec": ">=1.1.5 <2.0.0",
"type": "range"
},
"_requiredBy": [
"#DEV:/"
],
"_resolved": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.1.6.tgz",
"_shasum": "a9d20e4d8da8f7212d4865f6006f9214c4b41a20",
"_shrinkwrap": null,
"_spec": "express-basic-auth@^1.1.5",
"_where": "/nodeapps/https-test/greenlock-express.js",
"author": {
"email": "me@lionc.de",
"name": "LionC"
},
"bugs": {
"url": "https://github.com/LionC/express-basic-auth/issues"
},
"dependencies": {
"basic-auth": "^2.0.1"
},
"description": "Plug & play basic auth middleware for express",
"devDependencies": {
"@types/express": "^4.16.0",
"express": "^4.16.4",
"mocha": "^5.2.0",
"should": "^11.2.1",
"supertest": "^3.3.0",
"typescript": "^2.9.2"
},
"directories": {},
"dist": {
"fileCount": 7,
"integrity": "sha512-fRh/UU2q/YhvY0/Pkzi3VcLyjIExveW2NOOnOGgO6yO0jKXt6zcKPVPWSrL8nlhlh+YEH5LOjz+CGFML5dJQNw==",
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJb0yYdCRA9TVsSAnZWagAA/L0P/jGAALdYVv1Y7zpRb0b+\nCCvkxVYpxaVQ8bMc0cuT6I+EaZSa1xBe3ayUyoldeUoxfFfiaiD8giAWNkXq\nnDgvximSoZyxQkPVq2inVSFDSVAKYzliz9htBV6AfW64bd0SK2d1wV7TZhZE\njnF6blWFtuNM/8pnqmfIOZKD3HywRnriURqSXpHgcU6foemlyDv3ak8FMnVj\nuJCl30wxX2nAU+lD4Cmzv8bohVP5+DORRqVcfTnhaXSUyV3QhPNkN+PC7ffe\nYbKTxs1wjnYDvv1nbisrD+kWyvnfF0EUBMRzpTHdWvrlq+R8r5On1db1ECK3\nlL3BfFPZb7hH6Y6YNRWljDwtjomhvDjn6AMTARZi1V59KJkGLDFIWWT8VrJb\n684pJprANpG4sj5ZIAILR5MY+HK/R494beU/IV7Up1TXspINmk59ebjkIl7Q\nD4kxJHukML5eLtDNynWaOGZx048v1ePQb0GqqBew2TXvhiBi316sfUdf0HaS\n/L+DjdVLiZKdx6upod1dybgx6uDssUa08ZLIrTl9HBrTsZd59FjBQM7pbt5I\n3THzfGIp3UhCxuq/b3B9khbW4IHllglxLAwjiiKp8TAJN/RbC71xbzRPqvtM\nIfOT9c8rfeiVe4cjvPb6uTfB6wGP35fH+PDupoxtfPa86Jdun+3N6vywqkt1\n5vHK\r\n=dEdE\r\n-----END PGP SIGNATURE-----\r\n",
"shasum": "a9d20e4d8da8f7212d4865f6006f9214c4b41a20",
"tarball": "https://registry.npmjs.org/express-basic-auth/-/express-basic-auth-1.1.6.tgz",
"unpackedSize": 27326
},
"gitHead": "1ea015d2c6942b5d170cec6ce6e1a32a7c042100",
"homepage": "https://github.com/LionC/express-basic-auth#readme",
"keywords": [
"auth",
"authentication",
"basic",
"express",
"http",
"middleware"
],
"license": "MIT",
"main": "index.js",
"maintainers": [
{
"name": "lionc",
"email": "me@lionc.de"
}
],
"name": "express-basic-auth",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+https://github.com/LionC/express-basic-auth.git"
},
"scripts": {
"check-dts": "tsc express-basic-auth.d.ts",
"test": "mocha test.js && npm run check-dts"
},
"types": "express-basic-auth.d.ts",
"version": "1.1.6"
}

256
express-server/node_modules/express-basic-auth/test.js generated vendored Normal file
View File

@ -0,0 +1,256 @@
const should = require('should')
const basicAuth = require('./index.js')
const express = require('express')
const supertest = require('supertest');
var app = express()
//Requires basic auth with username 'Admin' and password 'secret1234'
var staticUserAuth = basicAuth({
users: {
'Admin': 'secret1234'
},
challenge: false
})
//Uses a custom (synchronous) authorizer function
var customAuthorizerAuth = basicAuth({
authorizer: myAuthorizer
})
//Same, but sends a basic auth challenge header when authorization fails
var challengeAuth = basicAuth({
authorizer: myAuthorizer,
challenge: true
})
//Uses a custom asynchronous authorizer function
var asyncAuth = basicAuth({
authorizer: myAsyncAuthorizer,
authorizeAsync: true
})
//Uses a custom response body function
var customBodyAuth = basicAuth({
users: { 'Foo': 'bar' },
unauthorizedResponse: getUnauthorizedResponse
})
//Uses a static response body
var staticBodyAuth = basicAuth({
unauthorizedResponse: 'Haaaaaha'
})
//Uses a JSON response body
var jsonBodyAuth = basicAuth({
unauthorizedResponse: { foo: 'bar' }
})
//Uses a custom realm
var realmAuth = basicAuth({
challenge: true,
realm: 'test'
})
//Uses a custom realm function
var realmFunctionAuth = basicAuth({
challenge: true,
realm: function (req) {
return 'bla'
}
})
app.get('/static', staticUserAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custom', customAuthorizerAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/challenge', challengeAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/async', asyncAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/custombody', customBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/staticbody', staticBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/jsonbody', jsonBodyAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realm', realmAuth, function(req, res) {
res.status(200).send('You passed')
})
app.get('/realmfunction', realmFunctionAuth, function(req, res) {
res.status(200).send('You passed')
})
//Custom authorizer checking if the username starts with 'A' and the password with 'secret'
function myAuthorizer(username, password) {
return username.startsWith('A') && password.startsWith('secret')
}
//Same but asynchronous
function myAsyncAuthorizer(username, password, cb) {
if(username.startsWith('A') && password.startsWith('secret'))
return cb(null, true)
else
return cb(null, false)
}
function getUnauthorizedResponse(req) {
return req.auth ? ('Credentials ' + req.auth.user + ':' + req.auth.password + ' rejected') : 'No credentials provided'
}
describe('express-basic-auth', function() {
describe('static users', function() {
const endpoint = '/static'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should reject without challenge', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(function (res) {
if(res.headers['WWW-Authenticate'])
throw new Error('Response should not have a challenge')
})
.expect(401, done)
})
it('should accept correct credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Admin', 'secret1234')
.expect(200, 'You passed', done)
})
})
describe('custom authorizer', function() {
const endpoint = '/custom'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Aloha', 'secretverymuch')
.expect(200, 'You passed', done)
})
})
describe('async authorizer', function() {
const endpoint = '/async'
it('should reject on missing header', function(done) {
supertest(app)
.get(endpoint)
.expect(401, done)
})
it('should reject on wrong credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('dude', 'stuff')
.expect(401, done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get(endpoint)
.auth('Aererer', 'secretiveStuff')
.expect(200, 'You passed', done)
})
})
describe('custom response body', function() {
it('should reject on missing header and generate resposne message', function(done) {
supertest(app)
.get('/custombody')
.expect(401, 'No credentials provided', done)
})
it('should reject on wrong credentials and generate response message', function(done) {
supertest(app)
.get('/custombody')
.auth('dude', 'stuff')
.expect(401, 'Credentials dude:stuff rejected', done)
})
it('should accept fitting credentials', function(done) {
supertest(app)
.get('/custombody')
.auth('Foo', 'bar')
.expect(200, 'You passed', done)
})
it('should reject and send static custom resposne message', function(done) {
supertest(app)
.get('/staticbody')
.expect(401, 'Haaaaaha', done)
})
it('should reject and send static custom json resposne message', function(done) {
supertest(app)
.get('/jsonbody')
.expect(401, { foo: 'bar' }, done)
})
})
describe('challenge', function() {
it('should reject with blank challenge', function(done) {
supertest(app)
.get('/challenge')
.expect('WWW-Authenticate', 'Basic')
.expect(401, done)
})
it('should reject with custom realm challenge', function(done) {
supertest(app)
.get('/realm')
.expect('WWW-Authenticate', 'Basic realm="test"')
.expect(401, done)
})
it('should reject with custom generated realm challenge', function(done) {
supertest(app)
.get('/realmfunction')
.expect('WWW-Authenticate', 'Basic realm="bla"')
.expect(401, done)
})
})
})