0

I have this example URL (referer).

http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback

I need to extract the value of the field 'state'. (which in this case would be 'somestate'). I have attempted to do it with substr() but I have to calculate the length of the base64 encoded substring. (which is not rather dynamic or safe)

As an alternative, I would convert it to JSON and try to extract it from JSON.

Many Thanks.

Eos Antigen
  • 368
  • 3
  • 13

3 Answers3

3

When dealing with standard data formats, don't try to roll your own parser with regular expressions or substr. It's a URL. Find an existing URL parser.

Node.js is distributed with one!

const referer = "http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback";
const parsed_url = new URL(referer);
const state = parsed_url.searchParams.get("state");
console.log(state);

NB: As the documentation mentions, Node has two URL parsers. The URL global and the url module which you can require. You need a relatively new version of Node to use the URL global. If you don't have it, then upgrade your Node.js install.

As an alternative, I would convert it to JSON and try to extract it from JSON.

This would be a red herring. To convert it to JSON you would first need to parse it. Once you have the parsed data, it would be still to convert it to JSON only to immediately convert it back to the parsed data you already have.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2
var url_string = "http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate=&redirect_uri=https://somestring.ngrok.io/api/oauthcallback"; // or you can use window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("state");
console.log(c);
yovopaw
  • 106
  • 4
1

You need to use Node.js's built in querystring module. You can use it like this:

var url = require('url');
var querystring = require('querystring');

var str = 'http://172.20.0.83:30923/oauth/authorize?client_id=8193654a-0b63-41df-953e-e6ae10807935&client_secret=somesecret&response_type=code&state=somestate&redirect_uri=https://somestring.ngrok.io/api/oauthcallback';

var state = querystring.parse(url.parse(str).query).state; // somestate
tbking
  • 8,796
  • 2
  • 20
  • 33
  • You are using the `url` module here. The [documentation](https://nodejs.org/api/url.html) says: **it is maintained solely for backwards compatibility with existing applications. New application code should use the WHATWG API** – Quentin Oct 12 '18 at 10:56
  • @Quentin yeah, but not a reason to leave a well known api which works. – tbking Oct 13 '18 at 12:56