美文网首页node
koa-jwt 使用详解

koa-jwt 使用详解

作者: 天涯笑笑生 | 来源:发表于2018-08-23 16:49 被阅读3132次

简介

  • github

  • 原文翻译

  • koa-jwt 主要提供路有权限控制的功能,它会对需要限制的资源请求进行检查

  • token 默认被携带在Headers 中的名为Authorization的键值对中,koa-jwt也是在该位置获取token

  • 也可以使用Cookie来提供令牌

  • app.use(jwt( { secret: 'shared-secret', passthrough:true }))
    通过添加一个passthrough选项来保证始终传递到下一个(中间件)

  • app.use(jwt({ secret: 'shared-secret', key: 'jwtdata' }))
    可以使用另外一ctx key来表示解码数据,然后就可以通过ctx.state.jwtdata代替ctx.state.user获得解码数据

  • secret 的值可以使用函数代替,以此产生动态的加密秘钥

  • koa-jwt 依赖于jsonwebtokenkoa-unless两个库的

koa-jwt 示例

  • 示例中使用了jwt-simple,也可以选择使jsonwebtoken
const Koa = require('koa')
const Router = require('koa-router')
const jwt = require('jwt-simple')

const koaBody = require('koa-body')

const koaJwt = require('koa-jwt') //路由权限控制

const app = new Koa()
const  router = new Router()

//秘钥
const jwtSecret = 'jwtSecret'
const tokenExpiresTime = 1000 * 60 * 60 * 24 * 7

// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(function(ctx, next){
    return next().catch((err) => {
        if (401 == err.status) {
            ctx.status = 401;
            ctx.body = 'Protected resource, use Authorization header to get access\n';
        } else {
            throw err;
        }
    });
});

app.use(koaJwt({secret:jwtSecret}).unless({
    path:[/^\/login/]
}))

router.get('/', (ctx) => {
    ctx.body = 'Hello koa-jwt'
})

// router.use(koaJwt(jwtSecret).unless({
//     path:[/^\/login/]
// }))

router.post('/login', koaBody(), (ctx) => {

    const user = ctx.request.body

    if (user && user.name){
        let payload = {
            exp:Date.now() + tokenExpiresTime,
            name:user.name
        }
        let token = jwt.encode(payload, jwtSecret)

        ctx.body = {
            user:user.name,
            code:1,
            token
        }
    }else {
        ctx.body = {
            code:-1
        }
    }
})

// router.use(koaJwt(jwtSecret))

router.get('/userInfo', ctx => {
    let token = ctx.header.authorization

    ctx.body = {
        token:token,
        user:ctx.state.user
    }

    //使用jwt-simple自行解析数据
   let payload = jwt.decode(token.split(' ')[1], jwtSecret);
    console.log(payload)
})

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
    console.log('app listening 3000...')
})
image.png
image.png

option

  • 可以直接参照源码设置
// Type definitions for koa-jwt 2.x
// Project: https://github.com/koajs/jwt
// Definitions by: Bruno Krebs <https://github.com/brunokrebs/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

import Koa = require('koa');

export = jwt;

declare function jwt(options: jwt.Options): jwt.Middleware;

declare namespace jwt {
    export interface Options {
        secret: string | Buffer;
        key?: string;
        tokenKey?: string;
        getToken?(opts: jwt.Options): string;
        isRevoked?(ctx: Koa.Context, decodedToken: object, token: string): Promise<boolean>;
        passthrough?: boolean;
        cookie?: string;
        debug?: boolean;
        audience?: string;
        issuer?: string;
        algorithms?: string[];
    }

    export interface Middleware extends Koa.Middleware {
        unless(params?: any): any;
    }
}

相关文章

  • koa-jwt 使用详解

    简介 github 原文翻译 koa-jwt 主要提供路有权限控制的功能,它会对需要限制的资源请求进行检查 tok...

  • JWT 鉴权

    使用 koa-jwt + jsonwebtoken 完成用户鉴权功能。项目地址:https://github.co...

  • 007.jwt验证

    cnpm i jwt-simple koa-jwt --save

  • 深入理解相机五(硬件抽象层HAL)

    一、Android 基础学习 Activity 使用详解 Service 使用详解 Broadcast 使用详解 ...

  • EventBus

    《EventBus使用详解(一)——初步使用EventBus》 《EventBus使用详解(二)——EventBu...

  • Android lifecycle 实战及使用进阶

    前言 Android lifecycle 使用详解 Android LiveData 使用详解 Android l...

  • Android中的AIDL

    Android中的AIDL使用详解 AIDL使用解析 Android进阶之AIDL的使用详解

  • koa-jwt

    http 是无状态协议。 访问一个服务器,不可能携带cookie。 必须是服务器得到这次请求,在下行响应报头中,携...

  • 字符串拼接详解

    1.使用 + 拼接字符串详解 2.使用StringBuilder拼接字符串详解 总结

  • RxSwift 使用详解

    Swift - RxSwift的使用详解1(基本介绍、安装配置) Swift - RxSwift的使用详解2(响应...

网友评论

    本文标题:koa-jwt 使用详解

    本文链接:https://www.haomeiwen.com/subject/tzjmiftx.html