Adonisjs - 向静态服务器中间件添加基本身份验证?

Adonisjs - Add basic auth to Static server middleware?

有没有办法通过基本身份验证来保护 adonis 中的静态服务资产?

无法将中间件添加到将命中来自 /public 目录的静态服务文件的路由...

因此,例如:

我想让浏览器提示基本身份验证,所以我尝试添加:

Route.get('/docs').middleware(['auth:basic'])

这将无法工作,因为:http://adonisjs.com/docs/4.0/http-context#_request_flow 因为静态服务在服务器中间件内部,发生在路由命中之前。

有什么实现方法吗?

写完这个问题后,我意识到我只需要编写自己的服务器中间件,它将 运行 在静态中间件之前......所以我结束了这样做:

  • app/Middleware/Server/StaticAuth.js

'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

  • 将此添加到 start/kernel.js
  • 中的服务器中间件列表

// ... contents of kernel.js file ...

const serverMiddleware = [
  'App/Middleware/Server/StaticAuth', // add it BEFORE Static middleware!
  'Adonis/Middleware/Static',
  'Adonis/Middleware/Cors'
]

  • 添加配置到config/auth.js

// ... contents of auth.js file ...

staticAuth: {
  realm: 'Protected data',
  username: 'admin',
  password: 'somePassword',

  protectedUrls: ['/', '/docs']  
}