【问题标题】:How do I pass access tokens from express server to react app, in a Oauth application?如何在 Oauth 应用程序中将访问令牌从快速服务器传递到反应应用程序?
【发布时间】:2021-12-15 09:15:07
【问题描述】:

我正在使用 express 服务器构建一个 react 应用程序,并使用 OAuth 2 安全地访问 intuit API。 express 服务器发送授权请求,然后在localhost:8000/callback 接收授权码,并在此将其转换为访问令牌。问题是这个访问令牌只能在 express 应用程序中访问 - 那么我如何将它发送到我的 react 前端,以便我可以使用它安全地从 react 进行 REST 调用?
我看过类似的问题,似乎有两种解决方案:使用 JWT,或者将访问令牌存储在本地存储中。我只是不知道从哪里开始使用这两种方法,因为我是学习 auth 的新手。

无论如何,我的应用程序的结构使得我的反应应用程序在localhost:3000 的开发服务器上运行,并代理请求到localhost:8000 的快速服务器。

这是快递应用:

'use strict';

require('dotenv').config();

/**
 * Require the dependencies
 * @type {*|createApplication}
 */
var express = require('express');
var app = express();
var path = require('path');
var OAuthClient = require('intuit-oauth');
var bodyParser = require('body-parser');
var ngrok =  (process.env.NGROK_ENABLED==="true") ? require('ngrok'):null;


/**
 * Configure View and Handlebars
 */
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(path.join(__dirname, '/public')));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(bodyParser.json())

var urlencodedParser = bodyParser.urlencoded({ extended: false });

/**
 * App Variables
 * @type {null}
 */
var oauth2_token_json = null,
    redirectUri = '';


/**
 * Instantiate new Client
 * @type {OAuthClient}
 */

var oauthClient = null;


/**
 * Home Route
 */
app.get('/', function(req, res) {

    res.render('index');
});

/**
 * Get the AuthorizeUri
 */
app.get('/authUri', urlencodedParser, function(req,res) {

    oauthClient = new OAuthClient({
        clientId: '*****',
        clientSecret: '*****',
        environment: 'sandbox',
        redirectUri: 'http://localhost:8000/callback'
    });

    var authUri = oauthClient.authorizeUri({scope:[OAuthClient.scopes.Accounting],state:'intuit-test'});
    res.send(authUri);
});


/**
 * Handle the callback to extract the `Auth Code` and exchange them for `Bearer-Tokens`
 */
app.get('/callback', function(req, res) {

    oauthClient.createToken(req.url)
       .then(function(authResponse) {
             oauth2_token_json = JSON.stringify(authResponse.getJson(), null,2);
         })
        .catch(function(e) {
             console.error(e);
         });

    res.redirect('http://localhost:3000')
});




/**
 * getCompanyInfo ()
 */
app.get('/getCompanyInfo', function(req,res){


    var companyID = oauthClient.getToken().realmId;

    var url = oauthClient.environment == 'sandbox' ? OAuthClient.environment.sandbox : OAuthClient.environment.production ;

    oauthClient.makeApiCall({url: url + 'v3/company/' + companyID +'/companyinfo/' + companyID})
        .then(function(authResponse){
            console.log("The response for API call is :"+JSON.stringify(authResponse));
            res.send(JSON.parse(authResponse.text()));
        })
        .catch(function(e) {
            console.error(e);
        });
});

app.get('/test', (req,res) => {
    res.send('hello from server')
})


const server = app.listen(process.env.PORT || 8000, () => {
    console.log(`???? Server listening on port ${server.address().port}`);
})

【问题讨论】:

    标签: node.js reactjs express oauth


    【解决方案1】:

    /authUri 请求由 浏览器 通过代理服务器发出,它的响应是对回调 URL 的 redirect。因此,回调 URL 也必须在前端服务器上(即http://localhost:3000/callback)。然后,代理服务器会将/callback 请求转发到快速服务器,并且快速服务器可以将访问令牌放入(仅 HTTP)cookie 中,然后(通过代理服务器)将其发送回浏览器。

    app.get('/callback', function(req, res) {
      oauthClient.createToken(req.url)
      .then(function(authResponse) {
        res.cookie("session", authResponse.getJson().access_token,
          {path: "/", httpOnly: true});
        res.redirect('http://localhost:3000');
      });
    });
    

    验证代理服务器是否保留了发送和接收的 cookie。

    然后,对于每个后续请求,浏览器都会(通过代理服务器)将 cookie 发送回快速服务器。

    (与本地存储不同,仅 HTTP 的 cookie 无法通过 JavaScript 访问,这提供了针对跨站点脚本攻击的额外保护。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 2021-05-03
      • 2022-01-21
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      相关资源
      最近更新 更多