簡體   English   中英

如何在節點 oAuth2 Server 中設置過期時間

[英]How can I set the expired time in node oAuth2 Server

我目前正在使用帶有節點 js 的 oAuth2 進行一個小項目。 帶有 express 和 node-oauth2-server 的 Node js 作為登錄等的完整服務...

一切正常,他們可以注冊,驗證他們的電子郵件地址並登錄(忘記密碼等尚未完成)但我無法設置令牌的過期值。

我最喜歡的實現是有或沒有永久登錄的登錄(在用戶界面中,登錄表單下方的這個常見小開關)。 此外,我想使用 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

您可以將accessTokenLifetime (以秒為單位)作為選項傳遞給 oAuth2Server 構造函數。

/* INIT */
app.oauth = oAuth2Server({
    model: oAuthModel,
    grants: ['password'],
    debug: debug,
    accessTokenLifetime: 4 * 60 * 60
})

如文檔( https://oauth2-server.readthedocs.io/en/latest/api/oauth2-server.html#new-oauth2server-options )中所述,您可以將任何用於身份驗證授權令牌方法的選項傳遞給oAuth2Server 構造函數選項。

accessTokenLifetime選項是令牌方法的一個選項( https://oauth2-server.readthedocs.io/en/latest/api/oauth2-server.html#token-request-response-options-callback )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM