Carrein
Carrein

Reputation: 3361

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

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?

Upvotes: 11

Views: 5579

Answers (4)

Lakmal Harshana
Lakmal Harshana

Reputation: 27

set the auth property in this way

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

Upvotes: 1

Professor Haseeb
Professor Haseeb

Reputation: 121

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/'
}

Upvotes: 5

schanzenbraut
schanzenbraut

Reputation: 21

I found this: https://github.com/lelylan/simple-oauth2/issues/279#issuecomment-569733862

Make sure that three urls are changed in the example. It works for me without {json: true}

This solution differs from the Microsoft tutorial

Upvotes: 1

oprimus
oprimus

Reputation: 406

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.

Upvotes: 5

Related Questions