• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

robin98sun/koa-jwt-redis-session: Pure JWT implementation using Redis as session ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

robin98sun/koa-jwt-redis-session

开源软件地址:

https://github.com/robin98sun/koa-jwt-redis-session

开源编程语言:

JavaScript 100.0%

开源软件介绍:

#JWT Redis Session for Koa 2

Pure JWT implementation using Redis as session storage for Koa 2, without any cookies

Quick Start

As middleware:

const koa = require('koa'),
      bodyParser = require('koa-bodyparser'),
      session = require('koa-jwt-redis-session')
// import session from 'koa-jwt-redis-session'

const app = new koa()
app.use(bodyParser())

app.use(session.default())

// If using import
// app.use(session()) 

app.use(async function(ctx, next){
    let views = ctx.session.views || 0
    ctx.session.views = ++views
    try{
       ctx.body = {views: ctx.session.views}
       await next()
    }catch(ex){
       console.error('something wrong:', ex)
       ctx.status = 500
       ctx.body = 'something wrong'
    }
})

app.listen(3333)

As a function:

// After used as middleware
// Somewhere when using as backdore
import {createSession, authoriseRequest} from 'koa-jwt-redis-session'

let openDoorHandler = async (ctx, next)=>{
    let userObj = {account: 'sneaky', password: 'open_the_back_door'};
    let token = await createSession(ctx, userObj);
    ctx.body = token;
    // Token is in JSON format: {token: ..... , expiresIn: 3600}
    // expiresIn is the expire time in seconds, default is 3600
}

let guardHandler = async (ctx, next)=>{
    let user = await authoriseRequest(ctx);
    if( user != undefined){
        ctx.body = user;
    }else{
        ctx.throw(new Error('Unauthorized'));
    }
}

Options

When creating session instance, you can pass in an option object

const sessionOptions = {
       // ......
}
app.use(session.default(sessionOptions))

// If using import
app.use(session(sessionOptions))

Here is the default option values

{
  jwt: {
    contentType: 'application/json',
    charset: 'utf-8',
    secret: 'koa-jwt-redis-session' + new Date().getTime(),
    authPath: '/authorize',
    registerPath: '/register',
    refreshTokenPath: '/refreshToken',
    expiresIn: 3600,
    accountKey: 'account',
    passwordKey: 'password',
    authHandler: function (account, password) {
            		if (account && password) {
 				let user = {};
				user[accountKey] = account;
				return user;
			}
			else return false;
        },
    registerHandler: function (account, password) {
           		if (account && password) {
				let user = {};
				user[accountKey] = account;
				return user;
			}
			else return false; 
        }
  },
  session: {
    sessionKey: 'session',
    sidKey: 'koa:sess',
  },
  redis: {
    port: 6379,
    host: '127.0.0.1',
    db: 0,
    ttl: 3600,
    options: {}
  }
}

Action flow

  1. Anonymous client post JSON user credential information { account: "...", password: "..." } to /register to register an account,
  2. or post to /authorize to get authorization
  3. Client get token in JSON like { token: "...", expiresIn: 3600 }, or an 401 error if not authorized
  4. From then on, client send every request by the http header: Authorization: Bearer <token>,
  5. or client would get 401 error if not authorized or token expired
  6. On the server side, afterward middlewares can operate ctx.session as will

Enjoy!




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
wejendorp/koa-timeout发布时间:2022-07-10
下一篇:
MrElvin/vue-koa-demo: 发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap