📜  express static auth - Javascript(1)

📅  最后修改于: 2023-12-03 14:41:04.511000             🧑  作者: Mango

Express Static Auth - Javascript

Introduction

Express Static Auth is a middleware for NodeJS created in Javascript. It is used to protect static files served by the ExpressJS server. It is a simple and convenient tool that allows for easy authentication of users before allowing them access to a folder or files inside it.

The middleware helps in handling the authentication process of users that's accessing static files such as CSS, JavaScript, and image files. It can be used with Express middleware to control security throughout your applications, making sure that only authorized users have access to sensitive content.

Installation

You can install Express Static Auth through npm using the following command:

npm install express-static-auth
Usage

Firstly, you need to require the middleware in your application.

const express = require('express');
const expressStaticAuth = require('express-static-auth');
Configuration

The middleware is configurable via options, such as:

  • path - The directory to protect
  • users - An object containing the list of authorized users and their passwords
  • loginPath - The path of the login page
  • pageTitle - The title of the login page
  • pageCSS - The path to the CSS file for the login page
  • errorPage - The path to a custom error page
  • logoutPath - The path to log the user out of the session
  • cookies - An object containing cookie options
  • session - The session middleware
  • logout - A function to run when the user logs out
  • onAuthenticated - A function to run when the user is authenticated
  • onUnauthorized - A function to run when the user is not authorized
const app = express();
const authOptions = {
  path: '/protected',
  users: { admin: 'password' },
  loginPath: '/login',
  pageTitle: 'My App Login Page',
  pageCSS: '/styles/login.css',
  errorPage: '/error',
  logoutPath: '/logout',
  cookies: {
    httpOnly: true,
    maxAge: 3600000, // 1 hour
  },
  session: {
    secret: 'mysecretpassword',
    resave: false,
    saveUninitialized: false,
  },
  logout: function(req, res) {
    res.redirect('/login');
  },
  onAuthenticated: function(req, res, next) {
    console.log('User successfully authenticated');
    next();
  },
  onUnauthorized: function(req, res, next) {
    console.log('User authentication failed');
    res.redirect('/login');
  },
};
app.use(expressStaticAuth(authOptions));
Login Page

When the authentication fails, the user will be redirected to the login page. You can customize the login page by passing in custom pageTitle and pageCSS options.

<!DOCTYPE html>
<html>
<head>
    <title>My App Login Page</title>
	  <link rel="stylesheet" href="/styles/login.css">
</head>
<body>
  <div class='form-container'>
    <h2>Login to access protected content</h2>
    <form method='post' action='/login'>
      <div>
        <label for='username'>Username:</label>
        <input type='text' placeholder='Enter your username' name='username' id='username'>
      </div>
      <div>
        <label for='password'>Password:</label>
        <input type='password' placeholder='Enter your password' name='password' id='password'>
      </div>
      <button type='submit'>Login</button>
    </form>
  </div>
</body>
</html>

The form should submit a POST request to the /login path with the username and password fields.

Logging Out

You can log out the user by calling the logout() function in the application.

app.get('/logout', (req, res) => {
    req.logout();
    res.redirect('/login');
});
Error Page

You can also specify the path to a custom error page to render when the authentication fails. This can be done by setting the errorPage option in the configuration object.

const authOptions = {
  ...
  errorPage: '/error',
  ...
};
<!DOCTYPE html>
<html>
<head>
  <title>Error - Access Denied</title>
</head>
<body>
  <h2>Error - Access Denied</h2>
  <p>You do not have the required permissions to access this content</p>
</body>
</html>
Conclusion

Express Static Auth is a middleware that enables developers to add an additional layer of security to their NodeJS applications. It is simple to use and configures to protect static files served by the ExpressJS server. The middleware also offers various options that make it highly flexible and easy to customize.