Node平台上的OAUTH2.0认证服务器搭建

1)安装express,vue
#mkdir startpoint & cd startpoint
#npm install express-generator
#node_modules\.bin\express IOVBackend
#cd IOVBackend
#npm install
#SET DEBUG=iovbackend:* & npm start
2)安装oauth2-server包
#npm install oauth2-server --save
#npm install express-oauth-server --save
oauth2-server的2.x版本已经被升级到3.0,由于api的变化,网上很多的例子不能使用。
oauth2-server需要adapter适应不同的web框架,官网支持express和koa。
3)增加一个model.js
/**
 * Constructor.
 */
function InMemoryCache() {
  var date_now = new Date();
  date_now.setDate(date_now.getDate()+1);
  this.clients = [{ clientId : 'thom', grants: ['authorization_code','password'], clientSecret : 'nightworld', redirectUris : ['http://localhost:3000'] }];
  this.tokens = [{user: {}, accessTokenExpiresAt:date_now, accessToken: 'foobar'}];
  this.users = [{ id : '123', username: 'thomseddon', password: 'nightworld' }];
}
/**
 * Dump the cache.
 */
InMemoryCache.prototype.dump = function() {
  console.log('clients', this.clients);
  console.log('tokens', this.tokens);
  console.log('users', this.users);
};
/*
 * Get access token.
 */
InMemoryCache.prototype.getAccessToken = function(bearerToken) {
  var tokens = this.tokens.filter(function(token) {
    return token.accessToken === bearerToken;
  });


  return tokens.length ? tokens[0] : false;
};


/**
 * Get refresh token.
 */
InMemoryCache.prototype.getRefreshToken = function(bearerToken) {
  var tokens = this.tokens.filter(function(token) {
    return token.refreshToken === bearerToken;
  });
  return tokens.length ? tokens[0] : false;
};
/**
 * Get client.
 */
InMemoryCache.prototype.getClient = function(clientId, clientSecret) {
  var clients = this.clients.filter(function(client) {
    return client.clientId === clientId;
  });
  if(clients.length > 0) {
    if(clientSecret === null) { //authroize handler doesn't care clientSecret
      return clients[0];
    } else if( clients[0].clientSecret === clientSecret) { //token handler does care clientSecret
      return clients[0];
    }
  }
  return false;
  // return clients.length ? clients[0] : false;
};
/**
 * Save Authorization code.
 */
InMemoryCache.prototype.saveAuthorizationCode = function(clientId, clientSecret) {
  return { authorizationCode: 123456 };
};
/**
 * Save token.
 */
InMemoryCache.prototype.saveToken = function(token, client, user) {
  this.tokens.push({
    accessToken: token.accessToken,
    accessTokenExpiresAt: token.accessTokenExpiresAt,
    clientId: client.clientId,
    refreshToken: token.refreshToken,
    refreshTokenExpiresAt: token.refreshTokenExpiresAt,
    userId: user.id
  });
  return { accessToken: 'foobar', client: {}, user: {} };
};
/*
 * Get user.
 */
InMemoryCache.prototype.getUser = function(username, password) {
  var users = this.users.filter(function(user) {
    return user.username === username && user.password === password;
  });
  return users.length ? users[0] : false;
};
/**
 * Export constructor.
 */
module.exports = InMemoryCache;

4)修改app.js
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var createError = require('http-errors');
var oauthserver = require('express-oauth-server');
var express = require('express');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
//var authsRouter = require('./routes/auths');

var app = express();
var mo = require('./model/model.js');
var memorymodel = new mo();

app.oauth = new oauthserver({
  model: memorymodel,
  grants:['password', 'authorization_code', 'refresh_token']
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(indexRouter);
/* authorize provide authorize code to clientside */
app.use('/oauth2/authorize', app.oauth.authorize(
  {
    authenticateHandler: {
      handle: (req, res) => {
        return req.body.user_id === 'u_thom';
      }
    }
  })
);
/* get access token */
app.use('/oauth2/token', app.oauth.token());
/* authenticate protect the resource api (client side should provide token) */
app.use('/api/v1/*', app.oauth.authenticate());
app.use('/api/v1/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
module.exports = app;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值