【发布时间】:2020-08-21 15:55:50
【问题描述】:
我目前正在使用带有节点 js 的 oAuth2 进行一个小项目。 带有 express 和 node-oauth2-server 的 Node js 作为其余的完整服务来登录等...
一切正常,他们可以注册,验证他们的电子邮件地址和登录(忘记密码等尚未完成) 但我无法设置令牌的过期值。
我最喜欢的实现是有或没有永久登录的登录(在 UI 中,登录表单下方的这个常见的小开关)。 我还想用 accessToken 存储客户端信息,比如浏览器、位置等。 这样用户就可以请求他当前登录的位置(就像您可以在 facebook 中一样)。
我的大部分 oAuth2 代码都来自本教程: https://blog.cloudboost.io/how-to-make-an-oauth-2-server-with-node-js-a6db02dc2ce7
我的主要问题是,我不知道在哪里处理数据。在我的注册(等)端点中,一切都通过我自己的中间件运行。但是使用 node-oauth2-server 我没有中间件。
谢谢!
克里斯
这是我的 server.js:
if(process.env.NODE_ENV === undefined)
process.env.NODE_ENV = "dev"
/* REQUIRE */
const oAuth2Server = require('node-oauth2-server');
const express = require('express');
const bodyParser = require('body-parser');
const util = require('util');
const dbCon = require('./subsystem/mySql')
const oAuthModel = require('./endpoints/auth/authModel')(dbCon);
/* CONST */
let port = 3000;
if(process.env.NODE_ENV !== 'production')
port = 3000;
else
port = 80;
const debug = true;
const app = express();
/* INIT */
app.oauth = oAuth2Server({
model: oAuthModel,
grants: ['password'],
debug: debug
})
/* ROUTER */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(app.oauth.errorHandler());
const authRoutes = require('./router/auth')(express.Router(), app, dbCon)
app.use('/auth', authRoutes);
app.all('*', (req, res) => {
res.status(404).send({message: "This service was not found"});
});
/* Start Server */
app.listen(port, () => {
console.log(`listening on port ${port} in ${process.env.NODE_ENV} mode`)
})
这是我的 authModel:
let dbCon;
module.exports = injectedDbCon => {
dbCon = injectedDbCon;
return {
getClient: getClient,
saveAccessToken: saveAccessToken,
getUser: getUser,
grantTypeAllowed: grantTypeAllowed,
getAccessToken: getAccessToken
}
}
const userDB = require('../user/userDB')(dbCon);
const authDB = require('./authDB');
function getClient(clientID, clientSecret, callback){
const client = {
clientID,
clientSecret,
grants: null,
redirectUris: null
}
callback(false, client);
}
function grantTypeAllowed(clientID, grantType, callback) {
console.log('grantTypeAllowed called and clientID is: ', clientID, ' and grantType is: ', grantType);
callback(false, true);
}
function getUser(email, password, callback){
console.log('getUser() called and email is: ', email, ' and password is: ', password, ' and callback is: ', callback, ' and is userDBHelper null is: ', userDB);
//try and get the user using the user's credentials
userDB.getUserFromCrentials(email, password)
.then(data => {callback(false,data[0][0])})
.catch(error => {callback(error,null)})
}
/* saves the accessToken along with the userID retrieved the specified user */
function saveAccessToken(accessToken, clientID, expires, user, callback){
console.log('saveAccessToken() called and accessToken is: ', accessToken,
' and clientID is: ',clientID, ' and user is: ', user, ' and accessTokensDBhelper is: ', authDB)
//save the accessToken along with the user.id
authDB.saveAccessToken(accessToken, user.id)
.then(data => {callback(null)})
.catch(error => {callback(error)})
}
function getAccessToken(bearerToken, callback) {
//try and get the userID from the db using the bearerToken
authDB.getUserIDFromBearerToken(bearerToken)
.then(data => {
const accessToken = {
user: {
id: data,
},
expires: null
}
callback(true,accessToken)
})
.catch(error => {callback(false,error)})
}
这是我的 authDB:
const dbCon = require('../../subsystem/mySql')
const saveAccessToken = (accessToken, userID) => {
return new Promise((resolve,reject) => {
//execute the query to get the user
dbCon.query(`INSERT INTO access_tokens (access_token, user_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE access_token = ?;`,[accessToken,userID,accessToken])
.then(data => {resolve(true)})
.catch(error => {reject(error)})
})
}
const getUserIDFromBearerToken = bearerToken => {
return new Promise((resolve,reject) => {
//create query to get the userID from the row which has the bearerToken
const getUserIDQuery = `SELECT * FROM access_tokens WHERE access_token = ?;`
//execute the query to get the userID
dbCon.query(getUserIDQuery,[bearerToken])
.then(data => {
if(data.results != null && data.results.length == 1)
resolve(data.results[0].user_id)
else
reject(false)
})
.catch(error => {reject(error)})
})
}
module.exports.saveAccessToken = saveAccessToken
module.exports.getUserIDFromBearerToken = getUserIDFromBearerToken
【问题讨论】: