diff --git a/lib/routes.js b/lib/routes.js index bff5869..6d2b565 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -95,6 +95,10 @@ const create = async function (server, { api, basedir, cors, vhost, handlers, ex if (operation.security && operation.security.length) { for (const secdef of operation.security) { const securitySchemes = Object.keys(secdef); + if (!securitySchemes.length) { + options.auth = options.auth || { access: {}, mode: 'optional' }; + options.auth.mode = 'optional'; + } for (const securityDefinitionName of securitySchemes) { let securityDefinition; diff --git a/test/fixtures/defs/pets_authed.json b/test/fixtures/defs/pets_authed.json index a77534c..cd4e7aa 100644 --- a/test/fixtures/defs/pets_authed.json +++ b/test/fixtures/defs/pets_authed.json @@ -39,7 +39,8 @@ "api_key2": [ "api2:read" ] - } + }, + {} ], "description": "Returns all pets from the system that the user has access to", "operationId": "findPets", @@ -96,6 +97,18 @@ } }, "post": { + "security": [ + { + "api_key": [ + "api1:read" + ] + }, + { + "api_key2": [ + "api2:read" + ] + } + ], "description": "Creates a new pet in the store. Duplicates are allowed", "operationId": "addPet", "produces": [ @@ -257,4 +270,4 @@ "in": "header" } } -} \ No newline at end of file +} diff --git a/test/fixtures/lib/stub-auth-token-scheme.js b/test/fixtures/lib/stub-auth-token-scheme.js index d966093..70b52dc 100644 --- a/test/fixtures/lib/stub-auth-token-scheme.js +++ b/test/fixtures/lib/stub-auth-token-scheme.js @@ -9,7 +9,7 @@ const register = function (server, options) { const token = request.headers.authorization; if (!token) { - throw Boom.unauthorized(); + throw Boom.unauthorized(null, 'stub-auth-token'); } try { diff --git a/test/test-auth.js b/test/test-auth.js index 5837b56..8b5ed5a 100644 --- a/test/test-auth.js +++ b/test/test-auth.js @@ -8,7 +8,7 @@ const StubAuthTokenScheme = require('./fixtures/lib/stub-auth-token-scheme'); Test('authentication', function (t) { t.test('token authentication', async function (t) { - t.plan(2); + t.plan(3); const server = new Hapi.Server(); @@ -36,6 +36,17 @@ Test('authentication', function (t) { url: '/v1/petstore/pets' }); + t.strictEqual(response.statusCode, 200, `${response.request.path} unauthenticated.`); + + response = await server.inject({ + method: 'POST', + url: '/v1/petstore/pets', + payload: { + id: '0', + name: 'Cat' + } + }); + t.strictEqual(response.statusCode, 401, `${response.request.path} unauthenticated.`); response = await server.inject({