【问题标题】:How can I use Basic authentication or JWT to the same route in Node?如何在 Node 中对同一路由使用基本身份验证或 JWT?
【发布时间】:2017-04-11 22:39:03
【问题描述】:

有没有办法使用 Koajs 在 Node 中使用 Basic Authentication 或 JWT 到同一路由?

我尝试了两种方法:

  1. 使用 Koa 中间件,当它有一个 Bearer 令牌或有一个基本身份验证时调用 next(),创建一个令牌并设置为 ctx.headers,但它不起作用

  2. 使用 koa-jwt 中的 getToken,但我无法返回加载用户信息以创建令牌的承诺。

【问题讨论】:

  • 您是否尝试在运行时在单个路由中在 jwt 或基本身份验证之间切换您的身份验证策略?这是你的问题吗?
  • 是的,取决于授权标头。
  • 你能展示一些你所做的示例代码吗?我将创建一个 checkAuth 路由中间件并测试令牌是有效的 jwt 还是有效的 base64 字符串,然后采取相应的行动。

标签: node.js jwt basic-authentication koa


【解决方案1】:

我发现了错误。打电话next()时忘记使用await

感谢@shanks,感谢您的时间!

这是工作代码:

route.js

'use strict'

import Koa from 'koa'
import mount from 'koa-mount'
import jwt from 'koa-jwt'
import basicAuth from './basic-auth'
import HomeRouter from './home/router'
import projectRouter from './v1/project/router'

export default new Koa().
  use(mount('/', HomeRouter.routes())).
  use(basicAuth).
  use(jwt({ secret: process.env.JWT_SECRET })).
  use(mount('/v1/projects', projectRouter.routes()))

basic-auth.js

'use strict'

import { chain } from 'lodash'
import jwt from 'jsonwebtoken'
import User from 'app/v1/user/model'

function _createAccessToken(user) {

  return jwt.sign({
    id: user.id,
    email: user.email
  }, process.env.JWT_SECRET)
}

export default async function basicAuth(ctx, next) {

  const header = ctx.headers.authorization
  if (/basic/i.test(header)) {

    const password = chain(header).
      split(' ').
      last().
      value()

    const user = await User.findOne({
      where: {
        apiPassword: Buffer.from(password, 'base64').toString()
      }
    })

    if (!user) return ctx.throw(401)
    const token = _createAccessToken(user)
    ctx.headers.authorization = `Bearer ${token}`
  }
  await next()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-30
    • 2017-11-02
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2017-06-13
    • 2016-07-01
    • 2019-04-03
    相关资源
    最近更新 更多