How to use express-jwt - 10 common examples

To help you get started, we’ve selected a few express-jwt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kriasoft / app-starter-kit / web / src / server.js View on Github external
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';

//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.resolve(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//
// Authentication
// -----------------------------------------------------------------------------
app.use(
  expressJwt({
    secret: config.auth.jwt.secret,
    credentialsRequired: false,
    getToken: req => req.cookies.id_token,
  }),
);
// Error handler for express-jwt
app.use((err, req, res, next) => {
  // eslint-disable-line no-unused-vars
  if (err instanceof Jwt401Error) {
    console.error('[express-jwt-error]', req.cookies.id_token);
    // `clearCookie`, otherwise user can't use web-app until cookie expires
    res.clearCookie('id_token');
  }
  next(err);
});
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / listened.route.js View on Github external
import express from 'express';
import expressJwt from 'express-jwt';
import ctrl from '../controllers/listened.controller';
import config from '../../config/config';

const router = express.Router(); // eslint-disable-line new-cap

router.use(expressJwt({ secret: config.jwtSecret }));

router.route('/')
  .get(expressJwt({ secret: config.jwtSecret }), ctrl.listByUser);

export default router;
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / relatedLink.route.js View on Github external
);

router.route('/:relatedLinkId/upvote')
  .post(
    expressJwt({ secret: config.jwtSecret })
    // TODO: refactor to have these into one call like upvote: [method1, method2,...]
    // upvoteHandlers
    , transferField({ source: 'relatedLink', target: 'entity' })
    , voteCtrl.findVote
    , voteCtrl.upvote // rename to upvoteHelper
    , voteCtrl.finish // IF we add a model.unlike we don't really need this..
  );

router.route('/:relatedLinkId/downvote')
  .post(
    expressJwt({ secret: config.jwtSecret })
    , transferField({ source: 'relatedLink', target: 'entity' })
    , voteCtrl.findVote
    , voteCtrl.downvote
    , voteCtrl.finish
  );

router.param('relatedLinkId', relatedLinkCtrl.load);

export default router;
github mmhansen / pear / server / index.js View on Github external
/*
 * Register express middleware
 */
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(responses)
if(process.env.NODE_ENV != 'test') {
  app.use(logger('dev'))
}

/*
 * Add authentication
 */
// this is decoding the token from the cookie
app.use(expressJwt({
  secret: config.auth.jwt.secret,
  credentialsRequired: false,
  getToken: req => req.cookies.id_token,
}));

app.use(passport.initialize());


if (process.env.NODE_ENV !== 'production') {
  app.enable('trust proxy');
}

app.get('/login/github',
  passport.authenticate('github', { scope: [ 'user:email' ] }));
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / company.route.js View on Github external
.get(
  expressJwt({ secret: config.jwtSecret })
  , loadFullUser
  , ensureIsAdmin
  , companyController.list
  )
  .post(
  expressJwt({ secret: config.jwtSecret })
  , loadFullUser
  , ensureIsAdmin // TODO: refactor to "loadAdmin"
  , companyController.create
  );

router.route('/findByLocalUrl/:localUrl')
  .get(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: false })
  , companyController.findByLocalUrl
);
router.route('/:companyId')
/** GET /api/company/:companyId - Get company */
.get(
  expressJwt({ secret: config.jwtSecret })
  , companyController.get
)
.delete(
  expressJwt({ secret: config.jwtSecret})
  , loadFullUser
  , ensureIsAdmin
  , companyController.delete
);

export default router;
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / post.route.js View on Github external
expressJwt({ secret: config.jwtSecret }),
    transferField({ source: 'post', target: 'entity' }),
    voteCtrl.findVote,
    voteCtrl.downvote,
    postCtrl.downvote,
    voteCtrl.finish
  );

router
  .route('/:postId/bookmark')
  .post(expressJwt({ secret: config.jwtSecret }), bookmarkCtrl.bookmark);

// todo: deprecate once all clients use bookmark
router
  .route('/:postId/favorite')
  .post(expressJwt({ secret: config.jwtSecret }), bookmarkCtrl.bookmark);

router
  .route('/:postId/unbookmark')
  .post(expressJwt({ secret: config.jwtSecret }), bookmarkCtrl.unbookmark);

// todo: deprecate once all clients use unbookmark
router
  .route('/:postId/unfavorite')
  .post(expressJwt({ secret: config.jwtSecret }), bookmarkCtrl.unbookmark);

router
  .route('/:postId/listened')
  .post(expressJwt({ secret: config.jwtSecret }), listenedCtrl.create);

router.param('postId', postCtrl.load);
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / forum.route.js View on Github external
.get(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: false }),
    forumCtrl.detail
  )
  .put(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: true }),
    forumCtrl.update
  )
  .delete(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: true }),
    forumCtrl.remove
  );

router.route('/:forumThreadId/upvote')
  .post(
    expressJwt({ secret: config.jwtSecret })
    // TODO: refactor to have these into one call like upvote: [method1, method2,...]
    // upvoteHandlers
    , transferField({ source: 'forumThread', target: 'entity' })
    , voteCtrl.findVote
    , voteCtrl.upvote // rename to upvoteHelper
    , voteCtrl.finish // IF we add a model.unlike we don't really need this..
  );
router.param('forumThreadId', forumCtrl.load);

export default router;
github steedos / object-server / packages / auth / src / jwt.ts View on Github external
throw new Error('jwt_token is needed!')
    }
    let decoded = jwt.decode(token, { complete: true });
    let payload = decoded.payload;
    let issuer = payload.iss;
    if (!issuer) {
      throw new Error('issuer is needed!')
    }
    let collection = getSteedosSchema().getObject('OAuth2Clients')
    let clients = await collection.find({ filters: `clientId eq '${issuer}'` })
    let clientInfo = clients[0]
    let secret = clientInfo ? clientInfo.clientSecret : ''
    if (!secret) {
      throw new Error('secret is needed!')
    }
    let verifiedPayload = jwt.verify(token, secret);
    let data = await getTokenInfo({ user: verifiedPayload })
    res.cookie('X-User-Id', data.userId, { maxAge: 90 * 60 * 60 * 24 * 1000, httpOnly: true });
    res.cookie('X-Auth-Token', data.authToken, { maxAge: 90 * 60 * 60 * 24 * 1000, httpOnly: true });
    let redirectUrl = verifiedPayload.redirect_url;
    res.redirect(301, redirectUrl);
  } catch (error) {
    console.error(error);
    res.status(500).send(error.messenger)
  }

})
github phiilu / mailman / src / api / index.js View on Github external
import { Router } from "express";
import jwt from "express-jwt";

import AuthenticationRouter from "./authenticationRouter";
import DomainRouter from "./domainRouter";
import AccountRouter from "./accountRouter";
import AliasRouter from "./aliasRouter";
import TlsPolicyRouter from "./tlspolicyRouter";

import { secret } from "../config";

const api = new Router();

api.use("/auth", AuthenticationRouter);
api.use("/domains", jwt({ secret }), DomainRouter);
api.use("/accounts", jwt({ secret }), AccountRouter);
api.use("/aliases", jwt({ secret }), AliasRouter);
api.use("/tlspolicies", jwt({ secret }), TlsPolicyRouter);

export default api;
github SoftwareEngineeringDaily / software-engineering-daily-api / server / routes / job.route.js View on Github external
.get(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: false })
    , jobController.get
  )
  .put(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: true })
    , jobController.update
  )
  .delete(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: true })
    , jobController.delete
  );

router.route('/:jobId/apply')
  .post(
    expressJwt({ secret: config.jwtSecret, credentialsRequired: true })
    , loadFullUser
    , upload.single('resume')
    , jobController.apply
  );

export default router;

express-jwt

JWT authentication middleware.

MIT
Latest version published 2 years ago

Package Health Score

64 / 100
Full package analysis