首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Adonisjs -向静态服务器中间件添加基本的auth?

Adonisjs -向静态服务器中间件添加基本的auth?
EN

Stack Overflow用户
提问于 2017-12-21 09:30:47
回答 1查看 1.4K关注 0票数 0

有没有办法通过基本方式保护adonis中静态服务的资产?

不可能在路由中添加中间件来访问/public dir中静态服务的文件.

因此,例如:

  • 我有/public/docs/index.html
  • 在服务adonis并访问localhost:3333/docs之后,我将获得index.html的内容。

我想要浏览以提示basic,所以我尝试添加:

代码语言:javascript
复制
Route.get('/docs').middleware(['auth:basic'])

这将不起作用,因为:flow感知服务静态在服务器中间件中,在路由命中之前发生。

有什么办法可以做到吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-21 09:53:06

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

  • app/中间件/Server/StaticAuth.js

代码语言:javascript
复制
'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中的服务器中间件列表中。

代码语言:javascript
复制
// ... 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

代码语言:javascript
复制
// ... contents of auth.js file ...

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47921873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档