有没有办法通过基本方式保护adonis中静态服务的资产?
不可能在路由中添加中间件来访问/public dir中静态服务的文件.
因此,例如:
我想要浏览以提示basic,所以我尝试添加:
Route.get('/docs').middleware(['auth:basic'])这将不起作用,因为:flow感知服务静态在服务器中间件中,在路由命中之前发生。
有什么办法可以做到吗?
发布于 2017-12-21 09:53:06
写完这个问题后,我意识到我只需要编写自己的服务器中间件,在静态中间件之前运行.所以我结束了这一切:
'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']
}
https://stackoverflow.com/questions/47921873
复制相似问题