Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-type is not JSON compatible while using Simple OAuth2 with NodeJS

Tags:

node.js

azure

I'm looking to authenticate using OAuth2 with Azure AD.

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);
  }

I followed the example provided by the repository but I'm getting an error Access Token error The content-type is not JSON compatible.

How can I authorize my OAuth2 with Microsoft Azure using NodeJS and Simple OAuth2?

like image 348
Carrein Avatar asked Oct 27 '19 08:10

Carrein


2 Answers

I came across this error also. The reason in my case was that the oAuth2 server was responding with a content-type header of text/plain - even though the body was actually JSON.

Changing the "json" configuration option to "force" in the http options of simple-oauth2 solved it for me.

like image 101
oprimus Avatar answered Nov 02 '22 20:11

oprimus


This is because you are only using tokenHost you also need to add tokenPath.

Example:

auth: {
    tokenHost: 'https://example.com',
    tokenPath: '/path/to/token/endpoint/'
}
like image 29
Professor Haseeb Avatar answered Nov 02 '22 21:11

Professor Haseeb