https://github.com/davidep87/secure-jws-session
Secure json web signature sessions with Redis
https://github.com/davidep87/secure-jws-session
jws nodejs redis session
Last synced: 2 months ago
JSON representation
Secure json web signature sessions with Redis
- Host: GitHub
- URL: https://github.com/davidep87/secure-jws-session
- Owner: davidep87
- Created: 2017-08-15T09:15:08.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2020-06-16T15:08:55.000Z (over 5 years ago)
- Last Synced: 2025-05-06T22:50:05.331Z (5 months ago)
- Topics: jws, nodejs, redis, session
- Language: JavaScript
- Size: 16.6 KB
- Stars: 4
- Watchers: 1
- Forks: 1
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Simple JWS Session handler
[](https://travis-ci.org/davidep87/secure-jws-session)
[](https://coveralls.io/github/davidep87/secure-jws-session?branch=master)![]()
![]()
![]()
##### Generate token with HS256 (HMAC with SHA-256) symmetric algorithm
##### Store token in redis to double check if token is generated by our machine##### Before you start to use this package you need to install Redis on your server or local machine
### How to use:
```javascript
npm install secure-jws-session --save
``````javascript
const Session = require('secure-jws-session')
const config = {
secret: '@2e£$1#1&$23_-!', // secret key (String)
serverHost: 'www.mdslab.org', // server hostname (String)
time: 1 // Set time expiration in minutes (Int)
}const auth = new Session(config)
```##### Generate a new token passing the user ID and the user type
```javascript
const token = await auth.createToken(1, 'user')
```##### Store the new session token in redis
```javascript
const session = {
user: 1,
token,
exp: new Date().getTime() + 1,
type: 'user'
}await auth.insert(session)
const result = await auth.check(token)
```##### Decode an existing token and check if is valid and generated by our machine:
```javascript
const decoded = await auth.decodeToken(token)
```### Using the session handler as middleware in Koa
#### Attach the session handler over the Koa context```javascript
app.context.auth = auth
```#### Create a Middleware
```javascript
module.exports = function(){return async function(ctx, next){
if(!ctx.request.body.token)
return ctx.body = { isLogged : false, token: false , message: 'You must provide a token for this route' }let status = await ctx.auth.check(ctx.request.body.token)
if(!status.isLogged)
return ctx.body = { isLogged : false, token: false , message: 'You are not logged in please do the log-in again' }await next()
}}
```#### Now you can use it in your route file
```javascript
const router = require('koa-router')()
const body = require('koa-body')()
const auth = require('./authMiddleware')router.post('/admin', body, auth(), yourProtectedFunction)
```## Author
Davide Polano