koajs

Node OAuth2 服务

Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with express in node.js

安装

npm install oauth2-server

入门

模块提供了两个中间件,一个为了认证和路由,一个是错误处理,使用它们,就像任何其他的中间件:

var express = require('express'),
    bodyParser = require('body-parser'),
    oauthserver = require('oauth2-server');

var app = express();

app.use(bodyParser()); // REQUIRED

app.oauth = oauthserver({
  model: {}, // 请参阅下面的说明
  grants: ['password'],
  debug: true
});

app.all('/oauth/token', app.oauth.grant());

app.get('/', app.oauth.authorise(), function (req, res) {
  res.send('Secret area');
});

app.use(app.oauth.errorHandler());

app.listen(3000);

运行node后, 访问 http://127.0.0.1:3000 将告诉你访问令牌找不到.

注意: 由于没有模式实际上是在这里实现, 钻研任何更深, i.e. 传递一个访问令牌, 只会导致服务器错误. 参看如下模型规范.

功能

  • 支持 authorization_code, password, refresh_token, client_credentials 和 extension (自定义) 认证类型
  • 隐式支持任何形式的存储器 例如: PostgreSQL, MySQL, Mongo, Redis...
  • 完整的测试套件

选项

  • string model
    • 模型对象 (见下文)
  • array grants
    • 你想支持的授予类型, 目前模块支持 passwordrefresh_token
    • 默认: []
  • function|boolean debug
    • 如果 true 错误将被记录到控制台. 您也可以通过自定义功能, 在这种情况下,函数将被调用,错误作为第一个参数
    • 默认: false
  • number accessTokenLifetime
    • 访问令牌寿命,秒
    • 如果 null, 令牌将被认为永不过期
    • 默认: 3600
  • number refreshTokenLifetime
    • 刷新令牌以寿命,秒
    • 如果 null, 令牌将被认为永不过期
    • 默认: 1209600
  • number authCodeLifetime
    • 验证码寿命,秒
    • 默认: 30
  • regexp clientIdRegex
    • 正则匹配认证代码针对监测模型前
    • 默认: /^[a-z0-9-_]{3,40}$/i
  • boolean passthroughErrors
    • 如果 true, non grant 错误不会被内部处理 (这样可以保证你的API的其余部分一致的格式)
  • boolean continueAfterResponse
    • 如果 true,即使响应已发送 next 将被称为 (你可能不希望这样)

模型设定

该模块需要一个模型对象,通过它的某些方面或存储,检索和自定义验证被抽象.

所有方法的最后一个参数是一个回调函数,它的第一个参数总是用来指示一个错误。

注意: 查看mongodb完整模型实例.

必选项

getAccessToken (bearerToken, callback)

  • string bearerToken
    • The bearer token (access token) that has been provided
  • function callback (error, accessToken)
    • mixed error
      • Truthy to indicate an error
    • object accessToken
      • The access token retrieved form storage or falsey to indicate invalid access token
      • Must contain the following keys:
        • date expires
          • The date when it expires
          • null to indicate the token never expires
        • string|number userId
          • The user id (saved in req.user.id)

getClient (clientId, clientSecret, callback)

  • string clientId
  • string|null clientSecret
    • If null, omit from search query (only search by clientId)
  • function callback (error, client)
    • mixed error
      • Truthy to indicate an error
    • object client
      • The client retrieved from storage or falsey to indicate an invalid client
      • Saved in req.client
      • Must contain the following keys:
        • string clientId

grantTypeAllowed (clientId, grantType, callback)

  • string clientId
  • string grantType
  • function callback (error, allowed)
    • mixed error
      • Truthy to indicate an error
    • boolean allowed
      • Indicates whether the grantType is allowed for this clientId

saveAccessToken (accessToken, clientId, expires, user, callback)

  • string accessToken
  • string clientId
  • date expires
  • object user
  • function callback (error)
    • mixed error
      • Truthy to indicate an error

authorization_code 授权类型必选项

getAuthCode (authCode, callback)

  • string authCode
  • function callback (error, authCode)
    • mixed error
      • Truthy to indicate an error
    • object authCode
      • The authorization code retrieved form storage or falsey to indicate invalid code
      • Must contain the following keys:
        • string|number clientId
          • client id associated with this auth code
        • date expires
          • The date when it expires
        • string|number userId
          • The userId

saveAuthCode (authCode, clientId, expires, user, callback)

  • string authCode
  • string clientId
  • date expires
  • mixed user
    • Whatever was passed as user to the codeGrant function (see example)
  • function callback (error)
    • mixed error
      • Truthy to indicate an error

password 授权类型必选项

getUser (username, password, callback)

  • string username
  • string password
  • function callback (error, user)
    • mixed error
      • Truthy to indicate an error
    • object user
      • The user retrieved from storage or falsey to indicate an invalid user
      • Saved in req.user
      • Must contain the following keys:
        • string|number id

refresh_token 授权类型必选项

saveRefreshToken (refreshToken, clientId, expires, user, callback)

  • string refreshToken
  • string clientId
  • date expires
  • object user
  • function callback (error)
    • mixed error
      • Truthy to indicate an error

getRefreshToken (refreshToken, callback)

  • string refreshToken
    • The bearer token (refresh token) that has been provided
  • function callback (error, refreshToken)
    • mixed error
      • Truthy to indicate an error
    • object refreshToken
      • The refresh token retrieved form storage or falsey to indicate invalid refresh token
      • Must contain the following keys:
        • string|number clientId
          • client id associated with this token
        • date expires
          • The date when it expires
          • null to indicate the token never expires
        • string|number userId
          • The userId

refresh_token 授权类型可选项

revokeRefreshToken (refreshToken, callback)

The spec does not actually require that you revoke the old token - hence this is optional (Last paragraph: http://tools.ietf.org/html/rfc6749#section-6)

  • string refreshToken
  • function callback (error)
    • mixed error
      • Truthy to indicate an error

extension grant 授权类型必选项

extendedGrant (grantType, req, callback)

  • string grantType
    • The (custom) grant type
  • object req
    • The raw request
  • function callback (error, supported, user)
    • mixed error
      • Truthy to indicate an error
    • boolean supported
      • Whether you support the grant type
    • object user
      • The user retrieved from storage or falsey to indicate an invalid user
      • Saved in req.user
      • Must contain the following keys:
        • string|number id

client_credentials 授权类型必选项

getUserFromClient (clientId, clientSecret, callback)

  • string clientId
  • string clientSecret
  • function callback (error, user)
    • mixed error
      • Truthy to indicate an error
    • object user
      • The user retrieved from storage or falsey to indicate an invalid user
      • Saved in req.user
      • Must contain the following keys:
        • string|number id

可选项

generateToken (type, callback)

  • string type
    • accessToken or refreshToken
  • function callback (error, token)
    • mixed error
      • Truthy to indicate an error
    • string|object|null token
      • string indicates success
      • null indicates to revert to the default token generator
      • object indicates a reissue (i.e. will not be passed to saveAccessToken/saveRefreshToken)
        • Must contain the following keys (if object):
          • string accessToken OR refreshToken dependant on type

扩展授权

You can support extension/custom grants by implementing the extendedGrant method as outlined above. Any requests that begin with http(s):// (as defined in the spec) will be passed to it for you to handle. You can access the grant type via the first argument and you should pass back supported as false if you do not support it to ensure a consistent (and compliant) response.

使用password授权类型实例

First you must insert client id/secret and user into storage. This is out of the scope of this example.

To obtain a token you should POST to /oauth/token. You should include your client credentials in the Authorization header ("Basic " + client_id:client_secret base64'd), and then grant_type ("password"), username and password in the request body, for example:

POST /oauth/token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=johndoe&password=A3ddj3w

This will then call the following on your model (in this order):

  • getClient (clientId, clientSecret, callback)
  • grantTypeAllowed (clientId, grantType, callback)
  • getUser (username, password, callback)
  • saveAccessToken (accessToken, clientId, expires, user, callback)
  • saveRefreshToken (refreshToken, clientId, expires, user, callback) (if using)

Provided there weren't any errors, this will return the following (excluding the refresh_token if you've not enabled the refresh_token grant type):

HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache

{
  "access_token":"2YotnFZFEjr1zCsicMWpAA",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA"
}

更新日志

See: https://github.com/thomseddon/node-oauth2-server/blob/master/Changelog.md

信用

Copyright (c) 2013 Thom Seddon

许可证

Apache, Version 2.0