有没有办法通过基本身份验证来保护adonis中的静态服务资产?
无法将路由器中间件添加到/ public目录中的静态服务文件......
所以,例如:
我想浏览器提示基本身份验证,所以我尝试添加:
{{1}}
这不起作用:http://adonisjs.com/docs/4.0/http-context#_request_flow Beacuase serve static是在服务器中间件内部发生的,它发生在路由命中之前。
任何想法如何实现这一目标?
答案 0 :(得分:1)
写完这个问题后,我意识到我只需要编写自己的服务器中间件,它将在静态中间件之前运行......所以我结束了这样做:
'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']
}