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

时间:2017-12-21 09:30:48

标签: node.js adonis.js

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

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

所以,例如:

  • 我有/public/docs/index.html
  • 在服务adonis并点击localhost后:3333 / docs我将获得index.html的内容

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

{{1}}

这不起作用:http://adonisjs.com/docs/4.0/http-context#_request_flow Beacuase serve static是在服务器中间件内部发生的,它发生在路由命中之前。

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

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

  • 应用程序/中间件/服务器/ 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']  
}