Giter Site home page Giter Site logo

nextjs-basic-auth-middleware's Introduction

nextjs-basic-auth-middleware

Adds basic auth support to Next.js projects using the official middleware approach (with a middleware file). Options can be set on the basic auth middleware and overridden using environment variables.

Compatibility table

Next.js version Plugin version
Next.js >=13.1 3.x
Next.js 12,13.0 2.x
Next.js 10,11 1.x

Installation

Run either of the following commands to add the package, based on your package manager of choice:

# NPM
npm install nextjs-basic-auth-middleware

# Yarn
yarn add nextjs-basic-auth-middleware

Usage

Next.js Middleware

The Next.js middleware functionality allows you to add basic auth in front of all your requests, see the Next.js Middleware documentation for more information.

It consists of 2 parts, createNextAuthMiddleware for checking and redirecting and createApiPage to create the API page that sends a 401 message.

You can use the createNextAuthMiddleware function to create a default middleware function that sends a NextResponse.next() when the auth passes:

    // middleware.ts
    import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware'

    export const middleware = createNextAuthMiddleware(options)

    export const config = {
        matcher: ['/(.*)'], // Replace this with your own matcher logic
    }

Optional

You can also use the nextBasicAuthMiddleware function to check basic auth in a bigger middleware function:

    import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware'

    export const middleware = (req) => {
        nextBasicAuthMiddleware(options, req)

        // Your other middleware functions here

        return NextResponse.next()
    }

⚠️ The middleware will still return a 401 and will quit processing the rest of the middleware. Add this middleware after any required work.

Setting environment variables

If you want to override credentials you can use the BASIC_AUTH_CREDENTIALS environment variable:

# Enables basic auth for user `test` with password `password`
BASIC_AUTH_CREDENTIALS=user:password

# You can set multiple accounts using `|` as a delimiter
BASIC_AUTH_CREDENTIALS=user:password|user2:password2

API

nextBasicAuthMiddleware()

nextBasicAuthMiddleware(req: NextApiRequest, res: http.ServerResponse, options)

The options object can contain any of the following options:

option description default value
pathname The path that the middleware redirects to /api/auth
users A list of users that can authenticate []
message Message to display to the user when authentication fails Authentication failed
realm Realm to show in the WWW-Authenticate header protected

The user object consists of the following required fields:

field description type
name The username string
password The password string

nextjs-basic-auth-middleware's People

Contributors

blurrah avatar dependabot[bot] avatar github-actions[bot] avatar jordie23 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

nextjs-basic-auth-middleware's Issues

How to work with nextBasicAuthMiddleware approach?

Hello!
Need your help with the nextBasicAuthMiddleware approach.
I need to have other rules in the middleware function so I'm trying to implement the nextBasicAuthMiddleware function.
createNextAuthMiddleware approach works.

How to implement the nextBasicAuthMiddleware function?

Next.JS 13 with App Router.

When I used the nextBasicAuthMiddleware function basic auth didn't work.
middleware.ts file in the root of the project

import { NextResponse } from 'next/server';
import { nextBasicAuthMiddleware } from 'nextjs-basic-auth-middleware'

const options = {users: [{ name: "test", password: "test" }]};
export const middleware = (req: any) => {
    nextBasicAuthMiddleware(options, req)
    return NextResponse.next()
}

export const config = {
    matcher: ['/(.*)'],
}

When I used the createNextAuthMiddleware function basic auth worked well.

import { createNextAuthMiddleware } from 'nextjs-basic-auth-middleware'

const options = {users: [{ name: "test", password: "test" }]};
export const middleware = createNextAuthMiddleware(options)

export const config = {
    matcher: ['/(.*)'],
}

What did I do wrong? How can I debug this problem?

BadRequestException leads 500 error

Thank you for providing awesome package.
I've noticed this middleware returns 500 if basicAuthentication throws BadRequestException

const currentUser = basicAuthentication(authHeader)
if (currentUser && compareCredentials(currentUser, credentialsObject)) {
return NextResponse.next()
}

Is it intentional?

Actual

$ curl localhost:3000 -H 'authorization: foo' -I
HTTP/1.1 500 Internal Server Error

Expectation

$ curl localhost:3000 -H 'authorization: foo' -I
HTTP/1.1 400 Bad Request

middleware.ts

import { createNextAuthMiddleware } from "nextjs-basic-auth-middleware";

export const middleware = createNextAuthMiddleware({
  users: [{ name: "foo", password: "bar" }],
});
export const config = {
  matcher: ["/(.*)"],
};

How to add to My Document?

I'm trying to add basicAuthMiddleware to MyDocument component but it's seem to be not working. Here is my custom Document Component, using TypeScript

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const sheet = new ServerStyleSheet()
    const originalRenderPage = ctx.renderPage
    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) => (props) =>
            sheet.collectStyles(<App {...props} />)
        })

      const initialProps = await Document.getInitialProps(ctx)

      // Add basic Auth middleware
      if (ctx.req && ctx.res) {
        await basicAuthMiddleware(ctx.req, ctx.res, {
          users: [{
            name: 'admin',
            password: 'admin'
          }],
        })
      }

      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        )
      }
    } finally {
      sheet.seal()
    }
  }
}

Authentication bypassed if the site is internationalised

Hi,

I've been testing your middleware and I realised that if you define some locales inside next.config.js, then the authentication is automatically bypassed. If the user clicks “Cancel” multiple times, they may even see the page's HTML as reported in #27 before 2.0.0.

Reproduction steps:

  1. Clone the repository: git clone [email protected]:labd/nextjs-basic-auth-middleware.git
  2. Navigate to nextjs-basic-auth-middleware/examples
  3. Install the dependencies: yarn
  4. Add some locales to next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
  i18n: {
    locales: ['en', 'es'],
    defaultLocale: 'en',
  },
  reactStrictMode: true,
  swcMinify: true,
}

module.exports = nextConfig
  1. Run the development server: yarn dev
  2. Open the page: http://localhost:3000/

Even before clicking on “Cancel”, inside the “Network” developer panel, you will see that the page's HTML is returned to the browser.

Authorize to user who doesn't input username or password!

This code would cause input.username = "" && input.password === password or input.username = username && input.password === "" authorized.
Apparently, it SHOULD NOT!

valid =
compare(
  user.name,
  requiredCredentials.find(item => item.name === user.name)?.name ?? ''
) && valid
valid =
compare(
  user.pass,
  requiredCredentials.find(item => item.password === user.pass)?.password ??
    ''
) && valid

Remove `paths` and describe matcher approach

The paths approach used in this package should be deprecated for the matcher configuration used in Next.js. Should show that it is deprecated and remove it in a later version.

Release v0.2.0

I've seen you removed the console.log(). Is it possible to release these changes?

[build]: n.end is not a function

Hello everyone, I've been trying to use this package to protect some of our under development pages but I'm running into an issue with next optimization step.

The package versions I'm using are

"next": "9.4.4",
"nextjs-basic-auth-middleware": "^0.1.0",

The error comes from an attempt by next to optimize the page

Creating an optimized production build

Compiled successfully.

Automatically optimizing pages ...
Error occurred prerendering page "/new". Read more: https://err.sh/next.js/prerender-error
TypeError: n.end is not a function

My code is as follows:

import Document, { DocumentContext, DocumentInitialProps } from 'next/document'
import basicAuthMiddleware from 'nextjs-basic-auth-middleware'

const credentials = process.env.BASIC_AUTH_CREDENTIALS.split(':')

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext): Promise<DocumentInitialProps> {
    await basicAuthMiddleware(ctx.req, ctx.res, {
      users: [{ name: credentials[0], password: credentials[1] }],
      includePaths: ['/new'],
    })

    const initialProps = await Document.getInitialProps(ctx)
    return initialProps
  }
}

export default MyDocument

It seems that the call to basicAuthMiddleware terminates/ends the response which may be used by the call to getInitialProps?

I've attempted at reordering the calls to see if that's the case, but I havent had any luck. One of my subpages is also using the getStaticProps, but removing it doesnt fix the build.

Edit: I realize I forgot to write that process.env.BASIC_AUTH_CREDENTIALS are set at build time, so that's not a potential source of the error

TypeError: Cannot read property 'url' of undefined

I created a _document.js to make a Custom Document, per https://nextjs.org/docs/advanced-features/custom-document

I'm getting the error TypeError: Cannot read property 'url' of undefined

Here's my pages/_document.js:

import Document, { Html, Head, Main, NextScript } from 'next/document'
import basicAuthMiddleware from 'nextjs-basic-auth-middleware'



class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx)
    await basicAuthMiddleware(ctx["req"], ctx["res"], {})
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head />
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

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.