Reputation: 1499
Is there a way to protect statically served assets in adonis via basic auth?
It's not possible to add middleware to route that will hit statically served files from /public dir...
So, for example:
I want to browser to prompt basic auth so I tried adding:
Route.get('/docs').middleware(['auth:basic'])
This will not work due: http://adonisjs.com/docs/4.0/http-context#_request_flow Beacuase serve static is inside Server middlewares which happens before route hit.
Any ideas how to achieve this?
Upvotes: 0
Views: 1641
Reputation: 1499
After writing this question I realized I just need to write my own server middleware that will run before static middleware... So I ended doing this:
'use strict'
const auth = use('basic-auth')
const config = use('Adonis/Src/Config').get('auth.staticAuth')
const validConfig = config && config.protectedUrls.length
class StaticAuth {
async handle({request, response}, next) {
// if there is no valid config... skip this middleware
if(!validConfig) return await next();
// check if currently visited url is matching protectedUrls
if(!request.match(config.protectedUrls)) return await next()
// access native node request/response
const req = request.request
const res = response.response
// gather credentials
const credentials = auth(req)
if (!credentials || credentials.name !== config.username || credentials.pass !== config.password) {
res.statusCode = 401
// send Basic Auth header so browser prompts user for user/pass
res.setHeader('WWW-Authenticate', `Basic realm="${config.realm || 'Protected Area'}"`)
res.end('Access denied')
}
await next()
}
}
module.exports = StaticAuth
// ... contents of kernel.js file ...
const serverMiddleware = [
'App/Middleware/Server/StaticAuth', // add it BEFORE Static middleware!
'Adonis/Middleware/Static',
'Adonis/Middleware/Cors'
]
// ... contents of auth.js file ...
staticAuth: {
realm: 'Protected data',
username: 'admin',
password: 'somePassword',
protectedUrls: ['/', '/docs']
}
Upvotes: 1