将Simple OAuth2与NodeJS一起使用时,内容类型与JSON不兼容



我希望使用带有Azure AD的OAuth2进行身份验证。

server.js

const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get("/authorize", async (req, res) => {
const credentials = {
client: {
id: "xxx",
secret: "xxx"
},
auth: {
tokenHost:
"xxx"
}
};
const oauth2 = require("simple-oauth2").create(credentials);
const tokenConfig = {
scope: "<scope>" 
};
const httpOptions = {};
try {
const result = await oauth2.clientCredentials.getToken(
tokenConfig,
httpOptions
);
const accessToken = oauth2.accessToken.create(result);
} catch (error) {
console.log("Access Token error", error.message);
}

我遵循了存储库提供的示例,但我得到了一个错误Access Token error The content-type is not JSON compatible

如何使用NodeJS和Simple OAuth2将我的OAuth2授权给Microsoft Azure?

我也遇到了这个错误。在我的案例中,原因是oAuth2服务器使用text/plain的内容类型标头进行响应,尽管正文实际上是JSON。

将simple-oauth2的http选项中的"json"配置选项更改为"force"为我解决了这个问题

这是因为您只使用tokenHost,还需要添加tokenPath

示例:

auth: {
tokenHost: 'https://example.com',
tokenPath: '/path/to/token/endpoint/'
}

我发现:https://github.com/lelylan/simple-oauth2/issues/279#issuecomment-569733862

请确保在示例中更改了三个url。它在没有{json: true}的情况下对我有效

此解决方案不同于Microsoft教程

以这种方式设置auth属性

auth: {
tokenHost: 'https://login.microsoftonline.com/common/',
tokenPath: 'oauth2/v2.0/token',
authorizePath: 'oauth2/v2.0/authorize',
},

最新更新