hlozancic
hlozancic

Reputation: 1499

Adonisjs - Add basic auth to Static server middleware?

Is there a way to protect statically served assets in adonis via basic auth?

It's not possible to add middleware to route that will hit statically served files from /public dir...

So, for example:

I want to browser to prompt basic auth so I tried adding:

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

This will not work due: http://adonisjs.com/docs/4.0/http-context#_request_flow Beacuase serve static is inside Server middlewares which happens before route hit.

Any ideas how to achieve this?

Upvotes: 0

Views: 1641

Answers (1)

hlozancic
hlozancic

Reputation: 1499

After writing this question I realized I just need to write my own server middleware that will run before static middleware... So I ended doing this:

  • 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

  • add this to list of server middlewares inside 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'
]

  • add configuration to config/auth.js

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

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

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

Upvotes: 1

Related Questions