How to use koa-jwt - 10 common examples

To help you get started, we’ve selected a few koa-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 soygul / koan / test / server / mocha.conf.js View on Github external
'use strict';

var config = require('../../server/config/config'),
    mongoSeed = require('../../server/config/mongo-seed'),
    app = require('../../app'),
    jwt = require('koa-jwt'),
    baseUrl = 'http://localhost:' + config.app.port + '/api',
    supertest = require('co-supertest'),
    request = supertest(baseUrl);

// create a valid jwt token to be sent with every request
var user = mongoSeed.users[1];
var token = jwt.sign({id: user._id, name: user.name, email: user.email}, config.app.secret);
token = 'Bearer ' + token;

// make request and token objects available
exports.request = request;
exports.token = token;

// initiate KOAN server before each test is run
// also drop and re-seed the test database before each run
console.log('Mocha starting to run server tests on port ' + config.app.port);
beforeEach(function *() {
  yield app.init(true);
});

// close the server after each test is done
afterEach(function (done) {
  app.server.close(done);
github luckcoding / hotchcms / server / src / app.ts View on Github external
render(app, {
  root: path.join(__dirname, './static'),
  layout: 'template',
  viewExt: 'html',
  cache: false,
  debug: true,
})

// 跨域
app.use(cors())

// 请求解析
app.use(koaBody())

// jwt
app.use(koaJwt({
  secret: JWT.secret,
  passthrough: true
}).unless({
  path: [/^\/apidocs/]
}))

app.use(valid()) // 参数验证
app.use(pipe()) // 通讯

// 路由
app
  .use(router.base)
  // .use(router.v1)
  .use(router.admin)

// 404
github bamlab / bam-api / src / koa / server.js View on Github external
const engine = new Engine({
  engineConfig: { apiKey: 'service:tychota-Bam-Api:1Z3thyxiVF84L4nF97NUmw' },
  graphqlPort: 3000, // GraphQL port
  endpoint: '/graphql', // GraphQL endpoint suffix - '/graphql' by default
  dumpTraffic: true,
});
engine.start();

// configure jwt middleware to connect to auth0, check the token and
const jwtConfig = {
  secret: jwksRsa.koaJwtSecret(config.get('Security.jwks')),
  ...config.get('Security.jwt'),
  passthrough: true,
};
app.use(koaJwt(jwtConfig));

app.use(engine.koaMiddleware());

// import the schema and mount it under /graphql
import schema from '../presentation/schema';
import getViewerAndRoles from '../business/utils/auth';

import { formatErrorGenerator } from 'graphql-apollo-errors';

// get the dataloader for each request
import * as business from '../business';
router.post(
  '/graphql',
  graphqlKoa(async ctx => {
    // create error formatter
    const formatErrorConfig = {
github ruiming / rss / index.js View on Github external
if (config.ENV === 'production') {
  mongoose.connect(`mongodb://${config.MONGODB.USER}:${config.MONGODB.PASSWORD}@${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
} else {
  mongoose.connect(`mongodb://${config.MONGODB.HOST}:${config.MONGODB.PORT}/${config.MONGODB.NAME}`)
}

app.use(ua())
app.use(cookies())
app.use(normal())
app.use(xsrf())

app.use(handel.routes())
    .use(handel.allowedMethods())

// Below needs JWT verfiy
app.use(jwt({
  secret: config.APP.JWT_KEY,
  algorithm: 'RS256'
}).unless({
  path: [/^\/static|css|js|img|fonts|favicon|manifest/]
}))

// API (Protected)
app.use(api.routes())
    .use(api.allowedMethods())
app.use(nghtml5())
app.listen(config.PORT)
github anotherleon / Test-Field / 11.koa+vue+ Element UI / server / src / routes / index.js View on Github external
module.exports = function () {
  const routesDir = __dirname // 如果不传参数,扫描目录默认为'routes'
  const router = require('koa-router')({prefix: `/api/${System.API_version}`})
  router.use(koaJWT({
    secret: System.JWT_secret
  }).unless({
    path: [/^\/api\/v1\/(user|admin|wx|upload|protocol|excel|everyday)\/(signin|auth|signature|image|new|base64|wx|order|type)/,
      '/api/v1/area',
      '/api/v1/banner',
      '/api/v1/district',
      // '/api/v1/specialty',
      // /^\/api\/v1\/specialty\/\d+/,
      '/api/v1/cuisine',
      '/api/v1/scene',
      '/api/v1/other'
      // '/api/v1/user',
    ]}))
  addRoutes(router, routesDir)
  return router.routes()
}
github ifactory-solutions / inside-server / src / index.js View on Github external
// routes
const router = new koaRouter();
loadRoutes(router);

if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'development_docker') {
  const corsOptions = {
    credentials: true,
    origin: '*',
  };
  app.use(cors(corsOptions));
}

app
  .use(bodyParser())
  .use(
    jwt({
      secret: process.env.JWT_KEY,
    }).unless({
      path: ['/', '/login'],
    }),
  )
  .use(logger())
  .use(router.routes())
  .use(
    router.allowedMethods({
      throw: true,
      notImplemented: () => new Boom.notImplemented(),
      methodNotAllowed: () => new Boom.methodNotAllowed(),
    }),
  )
  .use(async context => {
    context.body = 'INSIDE API';
github hongymagic / k2 / src / server.js View on Github external
import bodyParser from 'koa-bodyparser';
import passport from './passport';

const app = new Koa();

if (process.env.NODE_ENV === 'development') {
  app.use(logger());
}
app.use(convert(cors({ credentials: true })));
app.use(bodyParser());
app.use(passport.initialize());

// Parse Authorization Header for JWT tokens, and set ctx.state.user if token is
// valid. Passthrough to middleware to make decisions on whether or not their
// routes require users. See src/middleware/validate-user.js
app.use(jwt({ secret: process.env.APP_SECRET, passthrough: true }));

// Custom API modules that define their own routes.
const modules = require('./modules');
modules(app);

export default app;
github muffin / server / routes / api.js View on Github external
log('Couldn\'t load user', err)
  }

  if (!user) {
    this.status = 400
    this.body = {
      error: 'User doesn\'t exist'
    }
    return
  }

  // Compare password with the one within the DB
  const isMatch = user.tryPassword(body.password)

  if (isMatch) {
    const token = jwt.sign(body, process.env.SESSION_SECRET, {
      expiresIn: 300
    })

    this.body = {
      token
    }

    return
  }

  this.status = 400

  this.body = {
    error: 'Wrong password'
  }
github caihg / vue-demos / vue2.x-koa2.x / server / controllers / user.js View on Github external
if (userInfo != null) { // 如果查无此用户会返回 null
    if (userInfo.password != data.password) {
      if (!bcrypt.compareSync(data.password, userInfo.password)) {
        this.body = { // 返回给前端的数据
          success: false,
          info: '密码错误!'
        }
      }
    } else { // 密码正确
      const userToken = {
        id: userInfo.id,
        name: userInfo.user_name,
        originExp: Date.now() + 60 * 60 * 1000, // 设置过期时间(毫秒)为 1 小时
      }
      const secret = 'vue-koa-demo'; // 指定密钥,这是之后用来判断 token 合法性的标志
      const token = jwt.sign(userToken, secret); // 签发 token
      this.body = {
        success: true,
        token: token
      }
    }
  } else {
    this.body = {
      success: false,
      info: '用户不存在!'
    }
  }
}
github muffin / server / routes / api / token.js View on Github external
if (!user) {
    ctx.status = 400

    ctx.body = {
      error: 'User doesn\'t exist'
    }

    return
  }

  // Compare password with the one within the DB
  const isMatch = user.tryPassword(body.password)

  if (isMatch) {
    const token = jwt.sign(body, process.env.SESSION_SECRET, {
      expiresIn: 300
    })

    ctx.body = { token }
    return
  }

  ctx.status = 400

  ctx.body = {
    error: 'Wrong password'
  }

  await next()
})

koa-jwt

Koa middleware for validating JSON Web Tokens

MIT
Latest version published 2 years ago

Package Health Score

59 / 100
Full package analysis

Popular koa-jwt functions