passport-oauth2 icon indicating copy to clipboard operation
passport-oauth2 copied to clipboard

How could I modify the strategy so that it has the ability to vary the content-type beyond application/x-www-form-urlencoded

Open CakeCrusher opened this issue 2 years ago • 0 comments

Here is everything I have tried: https://chat.openai.com/share/cda16915-b97e-48de-836b-62501ab93041

Content-Type is decided in the oauth package here https://github.com/ciaranj/node-oauth/blob/0749d671f04b684ca255d6ff5340ae3efe711d9a/lib/oauth2.js#L191

The goal is to give the third party I'm authenticating, the ability to indicate content-type of they their tokenURL,, therefore changing the way the request is made.

The most promising solution thus far has been something along the lines of this (it did not work):

import { OAuth2Strategy as OriginalOAuth2Strategy } from 'passport-oauth2';

class DynamicContentTypeOAuth2Strategy extends OriginalOAuth2Strategy {
  contentType: string;

  constructor(options: any, verify: any) {
    super(options, verify);
    this.contentType = options.contentType || 'application/x-www-form-urlencoded';
  }

  getOAuthAccessToken(code: string, params: any, callback: any) {
    let post_data;
    if (this.contentType === 'application/json') {
      post_data = JSON.stringify({
        ...params,
        code: code,
      });
    } else {
      post_data = new URLSearchParams({
        ...params,
        code: code,
      }).toString();
    }

    const post_headers = {
      'Content-Type': this.contentType,
      'Content-Length': Buffer.byteLength(post_data),
    };

    this._oauth2._request(
      'POST',
      this._oauth2._getAccessTokenUrl(),
      post_headers,
      post_data,
      null,
      (err, data, response) => {
        if (err) return callback(err);
        let results;
        try {
          results = JSON.parse(data);
        } catch (e) {
          return callback(e);
        }
        const accessToken = results.access_token;
        const refreshToken = results.refresh_token;
        delete results.refresh_token;
        callback(null, accessToken, refreshToken, results);
      }
    );
  }
}

CakeCrusher avatar Aug 19 '23 13:08 CakeCrusher