1.3 鉴权的几种方法

    cookie  存储机制,http 本身是无状态的  cookie 是存储http状态
    cookie-session  可以自定义加密 使用redis  或mongoose做session持久化存储

2 oauth2 一种新的协议

  1. 解决的问题:实现第三方登录给三方服务一些简单的用户信息具体解决第三方的授权问题和密码问题

  2. 方法:客户端和服务提供商之间提供了一个授权层,客户端不能直接登录服务提供商,只能登录授权层,与用户的密码不同,可以在登录的时候指定授权层的令牌的范围和有效期,服务提供商根据令牌的权限范围和有效期想客户端开放资料

  3. 客户端的授权模式由四种授权码模式,简化,密码,客户端模式

  4. 授权码模式就是用户同意后服务器给客户端一个授权码,然后客户端与服务端重新核实。

  5. 客户端模式适合还需要用户来注册的可以拿到用户较多信息

3 jwt json web token

实现

router.get('/login', function(req, res, next) {
  const { username } = req.query
  const user = {
    username,
    expireAt: Date.now().valueOf() + 20 * 60 * 1000 //增加一个过期时间 来控制安全
  }
  const token = JWT.sign(user, 'asdasfgfdghd;lk;')
  res.send(token)
})

发射到客户端后会产生一个由三部分产生的字符串 1 部分是一个 base64 编码的字符串 解码后得到 {alg:加密格式(hs256),typ:类型(jwt)} 2 签名数据 发送的东西,和时间戳 3 不能解码的密钥 使用算法加密的

使用的时候

# 把发送过来的token 放在请求头中

router.get('/hello', (req, res, next) => {
  const auth = req.get('Autchorization')
  if (!auth) return res.send('no auth')
  if (!auth.indexOf('Bearer') === -1) res.send('no auth')
  const token = auth.split('Brarer')[1]
  const user = JWT.verify(token, 'asdasfgfdghd')
  if (user.expireAt < Date.now().valueOf) {
    res.send('no auth')
  }
  res.send(user)
})

密码加密

crypto 库 pbkdf2 密码加密 加密由两个方法 1 同步 2 异步方法实现加密

onst crypto = require('crypto')
const pbkdf2Async = require('bluebird').promisify(crypto.pbkdf2)//给回调函数一个异步模块 使用蓝鸟

  (async () => {
    const {
      username,
      password
    } = req.body
    const cipassword = await crypto.pbkdf2Async(password, 'asdafdsfsdf', 1000, 512, 'sha256')
    const created = User.insert({
      username,
      password: cipassword
    })
  })()
    .then(r => {})
    .catch(e => {})

最好密码使用分库分表 不和用户的基本信息在同一个数据库内这样会比较安全

Last updated

Was this helpful?