start a secure web service with auth0 in typescript

To start a secure web service with Auth0 in Typescript, you can follow these steps:

  1. Create a new Node.js project with TypeScript installed.
index.ts
mkdir my-project && cd my-project
npm init -y
npm install typescript
69 chars
4 lines
  1. Install the required dependencies:
index.ts
npm install express cors body-parser jsonwebtoken jwks-rsa
npm install @types/express @types/cors @types/body-parser @types/jsonwebtoken
137 chars
3 lines
  1. Create a new file named server.ts and add the following code:
index.ts
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import * as jwt from 'jsonwebtoken';
import * as jwksRsa from 'jwks-rsa';

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

const port = 3000;

// Define your Auth0 settings
const authConfig = {
  domain: 'YOUR_DOMAIN.auth0.com',
  audience: 'http://localhost:3000',
};

// Define your custom middleware function to validate JWT
export function checkJwt(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }

  try {
    const decodedToken = jwt.verify(
      token,
      jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,
      })
    );

    req.user = decodedToken;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Invalid token' });
  }
}

// Example endpoint that requires authentication
app.get('/api/private', checkJwt, (req, res) => {
  res.json({
    message: 'Hello from a private API endpoint',
  });
});

// Start the server
app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
1360 chars
58 lines
  1. Replace YOUR_DOMAIN and http://localhost:3000 in the authConfig object with your own values.

  2. Start the server by running tsc to compile TypeScript to JavaScript, and then node dist/server.js to start the server.

index.ts
tsc
node dist/server.js
24 chars
3 lines
  1. Access the http://localhost:3000/api/private endpoint from your browser or API client, passing a valid JWT token in the Authorization header.

gistlibby LogSnag