【发布时间】: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