鉴权

使用session/cookie

cookie.js
const http = require('http');
// 一般需要存到数据库里
const session = {}
http.createServer((req, res) => {
    if (req.url === './favicon.ico') {
        res.end('')
    }
    console.log('cookie', req.headers.cookie);
   
    const sessionKey = 'sid';
    const cookie = req.headers.cookie;
    if (cookie && cookie.indexOf(sessionKey) >= 0) {
        res.end('welcome back');
       
        const pattern = new RegExp(`${sessionKey}=([^;]+);?\s*`);
        const sid = pattern.exec(cookie)[1];
        console.log('pattern', pattern);
        console.log('sid', sid);
        
        console.log('session', sid, session, session[sid]);
    } else {
        const sid = (Math.random() * 89999).toFixed();
        // 设置cookie
        res.setHeader('Set-Cookie', `${sessionKey}=${sid}`);
        session[sid] = {name: 'izengx'};
        res.end('hi new one')
    }
    
}).listen(3000)
session.js
const koa = require('koa');
const app = new koa();
const session = require('koa-session');

// 使用redis存储session
const redisStore = require('koa-redis');
const redis = require('redis');
const redisClient = redis.createClient(6379, 'localhost');
const wraper = require('co-redis');
const client = wraper(redisClient);

// 加密的key
app.keys = ['some secret'];

const SESS_CONFIG = {
    key: 'kkb:sess',
    maxAge: '86400000',
    httpOnly: true,
    signed: true,   // 哈希签名
    store: redisStore({client}),    // 存储到redis
}

// 注册
app.use(session(SESS_CONFIG, app))
// 验证是否存到redis了,把redis里存的值打印出来看看
app.use(async (ctx, next) => {
    const keys = await client.keys('*');
    keys.forEach(async key => {
        console.log(await client.get(key));
    });
    await next();
})

app.use(ctx => {
    if (ctx.path === '/favicon.ico') return 
   
    let n = ctx.session.count || 0;
    ctx.session.count = ++n;
    ctx.body = `第${n}次访问`
})
app.listen(3000);

你可能感兴趣的:(node.js)