Code Monkey home page Code Monkey logo

nuxt-basic-auth-module's Introduction

Nuxt.js basic auth module

code style: prettier donate: Patreon License: MIT NPM version All Contributors NPM downloads codecov

f2653ad0d131606c49edb3f605cbf547

Provide basic authentication to your Nuxt.js application

https://www.npmjs.com/package/nuxt-basic-auth-module

Installation

$ yarn add nuxt-basic-auth-module # or npm install

Usage

Edit your nuxt.config.js

export default {
  // ...
  modules: [
    'nuxt-basic-auth-module'
  ],
  basic: {
    name: 'AUTH USER NAME HERE',
    pass: 'AUTH PASSWORD HERE',
    enabled: process.env.BASIC_ENABLED === 'true' // require boolean value(nullable)
  },

  // ...
}

Arguments

enabled

  • type: Boolean
  • default: false
  • required: false

Whether to activate this module. If false, module registration is skipped.

name

  • type: String | Function
  • required: true

Basic Auth user name.

The function passes req as an argument and must return the username as string.

pass

  • type: String | Function
  • required: true

Basic Auth user password.

The function passes req as an argument and must return the password as string.

message

  • type: String,
  • default: 'Please enter username and password'
  • required: false

Message to be displayed during basic authentication.

match

  • type: String(regex literal) | Function
  • required: false

The target path. This allows you to set up basic authentication that is limited to routes that match regular expression literals or where the function returns true.

The function passes req as an argument.

License

MIT

https://github.com/potato4d/nuxt-basic-auth-module/blob/master/LICENSE

Contributors

Thanks goes to these wonderful people (emoji key):


Takuma HANATANI

๐Ÿ’ป ๐Ÿšง ๐Ÿ“– ๐Ÿ›

Anthony Fu

๐Ÿ’ป

Jleroy

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

nuxt-basic-auth-module's People

Contributors

allcontributors[bot] avatar amr2812 avatar antfu avatar dependabot[bot] avatar jleroy-gm avatar potato4d avatar renovate-bot avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nuxt-basic-auth-module's Issues

Module breaks subsequent axios requests using Basic Auth credentials from .env

When installing this module axios requests subsequent to the login get sent with the wrong credentials.
Instead of using credentials stored within an .env file, the requests get sent with the credentials that where used for the basic-auth dialogue.

const auth = {
  username: process.env.kirbyEmail,
  password: process.env.kirbyAuth
}

async getPages({ commit }, locale) {
    try {
      const pages = await this.$axios.$get(baseURL + '/rest/site/children', {
        auth,
        headers: { 'x-language': locale },
        params: { select: 'content, id, children, status, template' }
      })
      return commit('setPages', pages)
    } catch (error) {
      console.error(error)
    }
  }

async nuxtServerInit({ dispatch, state }) {
    const locale = state.i18n.locale
    await dispatch('getPages', locale)
  }

Any idea how this could be fixed?

Does this work when the target is static ?

So yeah, basically this module is working great while nuxt dev.

But when nuxt generate then nuxt start, so it's giving me

Environment: production
Rendering: server-side
Target: static

It just ignore the whole security even with enabled: true.

Wanted to be sure what is happening there. ๐Ÿ˜„

Basic Auth Fail for the other api Calling

image
after input the userName and password, it will bring the basic html page.
but if it calls some more api, it will show the basic-auth again, and the username and password do not work anymore.

Disable for proxy

When a proxy is used (i.e. with axios) the auth-module also restricts access to the proxy routes, which makes a api call impossible.
Is there a way do disable the authentication for all proxy routes?

I tried it with regex (/^((?!api-route1|api-route2).)*$/) in the match option, but this seems not to work.

"undefined" as enabled option doesn't skip module registration

When giving the "enabled" option "undefined" as value, for example when using ENV variables that are not present on all environments, the module is still activated.

I would propose to change this so that "undefined" also skips the registration. Thoughts? I can make a pull request if this sounds good to everyone.

Not working with nuxt3

Hi!

I am having an error when trying to get this plugin to work with Nuxt3. Should be working, or is this plugin only intended to run with Nuxt2?

โ„น Register basic auth module to server middleware  

 ERROR  Cannot start nuxt:  Cannot read properties of undefined (reading 'handle')                                                                                                              

  at Function.use (node_modules/connect/index.js:87:21)
  at Object.set [as setLegacyMiddleware] (node_modules/@nuxt/nitro/dist/index.mjs:1875:13)
  at node_modules/nuxt3/dist/index.mjs:852:17
  at async initNuxt (node_modules/nuxt3/dist/index.mjs:945:3)
  at async load (node_modules/nuxi/dist/chunks/dev.mjs:6717:9)
  at async Object.invoke (node_modules/nuxi/dist/chunks/dev.mjs:6756:5)
  at async _main (node_modules/nuxi/dist/chunks/index.mjs:384:7)

This is my nuxt.config.js

export default defineNuxtConfig({
  modules: [
    [
      'nuxt-basic-auth-module'
    ]
  ],
  alias: {
    images: resolve(__dirname, './public/images')
  },
  vite: {
    build: {
      chunkSizeWarningLimit: 1000
    }
  },
  basic: {
    name: 'AUTH USER NAME HERE',
    pass: 'AUTH PASSWORD HERE',
    enabled: 'true' // require boolean value(nullable)
  },
})

Add possibility to change basic auth credentials based on hostname / route or any custom condition

Hey !

Would be nice to allow function for name & pass option.
That way we would be able to adapt credentials for each route or each domain/subdomain if wanted (like in my use case).

I tried to do it myself the hard way like below, and it seems to be working like a charm :

middleware.js

const createMiddleware = options => {
  return (req, res, next) => {
    try {
      let enabled = true
      let match = options.match
      let name = options.name
      let pass = options.pass

      if (typeof name === 'function') {
          options.name = name(req)
      }

      if (typeof pass === 'function') {
          options.pass = pass(req)
      }

      if (typeof match === 'function') {
        enabled = match(req)
      }
      else if (match instanceof RegExp) {
        enabled = match.test(req.url)
      }
      else if (typeof match === 'string') {
        enabled = match === req.url 
      }
      
      if (!enabled || auth(options, req)) {
        return next()
      }
    } catch (e) {
      //
    }
    res.statusCode = 401
    res.setHeader('WWW-Authenticate', createBasicMessage(options))
    return res.end()
  }
}

nuxt.config.js

basic: {
        name({headers}){
            const currentHostname = headers['x-forwarded-host'] ? headers['x-forwarded-host'] : headers.host;
            switch (currentHostname) {
                case 'myhost.com':
                    return 'my_login'
                default:
                    return 'my_default_login';
            }
        },
        pass({headers}){
            const currentHostname = headers['x-forwarded-host'] ? headers['x-forwarded-host'] : headers.host;
            switch (currentHostname) {
                case 'myhost.com':
                    return 'my_password'
                default:
                    return 'my_default_password';
            }
        },
        match({headers}) {
            const enabledAuthHostnames = [
                'myhost.com',
                // ...
            ]
            const currentHostname = headers['x-forwarded-host'] ? headers['x-forwarded-host'] : headers.host;
            return enabledAuthHostnames.includes(currentHostname)
        }
}

Maybe my case is quite specific with the hostname conditions i added (i need to enable the basic Auth only on a few hostnames that my multisites application can hold), but it would at least give the choice for the developer to set whatever he want as condition within the function (route / domain / ...).
As well as the current match option, the classic string format would still be the default usage of the options for the simple use case.

What do you think to this possible improvement ?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update actions/cache action to v4
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/test.yml
  • actions/checkout v1
  • actions/cache v1
  • actions/setup-node v1
npm
package.json
  • basic-auth ^2.0.1
  • consola ^2.3.2
  • cheerio 1.0.0-rc.12
  • codecov 3.8.3
  • jest 28.1.3
  • jsdom 19.0.0
  • nuxt 2.15.8
  • prettier 2.7.1
  • puppeteer 13.7.0
  • request 2.88.2
  • request-promise-native 1.0.9
  • standard-version 9.5.0

  • Check this box to trigger a request for Renovate to run again on this repository

Possible security issue

Hello,

I have noticed that this middleware doesn't cover files like Nuxt.js runtime/chunk files or static assets.
If this is being used in an admin panel for example, then some important data may be leaked.
In my opinion it should cover the whole application, not only the pages.

To reproduce:
Try viewing file like 127.0.0.1:3000/_nuxt/runtime.js or some static asset.

Here's how I fixed it myself:
Running this middleware using native Express instead of Nuxt middleware will make it run before anything else,
therefore protecting internal Nuxt files or static assets.

It can be done by chaning the way of creating middleware from:
this.addServerMiddleware(middleware)
to this:
this.nuxt.server.app.use(middleware)
(nuxt.server doesn't exist on build time, so it needs to be null checked)

Unfortunately I have no time to make a pull request.

If this is not an issue, then I believe it should be mentioned in the documentation that this middleware doesn't cover files like that.

Router support

In my case, I have a demand to auth some paths like /admin.

Could we have a field in config to specific which routes should be managed by this module?

Something like this:

module.exports = {
  modules: [
    'nuxt-basic-auth-module'
  ],
  basic: {
    name: 'AUTH USER NAME HERE',
    pass: 'AUTH PASSWORD HERE',
    match(route) {
        // return true to enable basic auth
        return route.path.startsWith('/admin')
    },
  },
  // ...
}

No Login Dialog on First Load Post Deploy

After deploying the application protected by this module, the site will not render the Basic Auth login dialog unless a hard reload is done.

The request for / hits the server and gets a 401 response with a www-authenticate: Basic realm, but no login dialog.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Pulling project into Nuxt Universal App and not running with default data

Hi all,

I've read the docs - there aren't many as its simple! But I've been trying to get this working for the last couple of hours, I had yarn add'd the module, listed the module under 'modules' in the nuxt config file, added the following to the project:

basic: { name: 'AUTH USER NAME HERE', pass: 'AUTH PASSWORD HERE', enabled: process.env.BASIC_ENABLED === 'true' // require boolean value(nullable) },

And no prompts are showing on app refresh, I've cleared the cache, restarted the app, nothign to seems to work and I'm not sure where to go from here. Any and all help appreciated.

EDIT: No errors are appearing in console.

Many thanks,
Kurtis Rogers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.