Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most clever way to parse a Facebook OAuth 2 access token string

Tags:

regex

It's a bit late, but I'm disappointed in myself for not coming up with something more elegant. Anyone have a better way to do this...

When you pass an OAuth code to Facebook, it response with a query string containing access_token and expires values.

access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.&expires=4554

Although if you request permission for offline access, there's no expires and the string looks like this:

access_token=121843224510409|2.V_ei_d_rbJt5iS9Jfjk8_A__.3600.1273741200-569255561|TxQrqFKhiXm40VXVE1OBUtZc3Ks.

I attempted to write a regex that would suffice for either condition. No dice. So I ended up with some really ugly Ruby:

s = s.split("=")
@oauth = {}
if s.length == 3
  @oauth[:access_token] = s[1][0, s[1].length - 8]
  @oauth[:expires] = s[2]
else
  @oauth[:access_token] = s[1]
end

I know there must be a better way!

like image 477
ryonlife Avatar asked May 13 '10 08:05

ryonlife


People also ask

What can I do with Facebook access token?

Tokens are Portable Otherwise, once you have an access token you can use it to make calls from a mobile client, a web browser, or from your server to Facebook's servers. If a token is obtained on a client, you can ship that token down to your server and use it in server-to-server calls.

How do I use OAuth on Facebook?

Under Products in the App Dashboard's left side navigation menu, click Facebook Login, then click Settings. Verify the Valid OAuth redirect URIs in the Client OAuth Settings section. state . A string value created by your app to maintain state between the request and callback.

Does OAuth2 support Facebook?

It's the only authentication protocol supported by the major vendors. Google recommends OAuth2 for all of its APIs, and Facebook's Graph API only supports OAuth2. The best way to understand OAuth2 is to look at what came before it and why we needed something different. It all started with Basic Auth.


2 Answers

Split on the & symbol first, and then split each of the results on =? That's the method that can cope with the order changing, since it parses each key-value pair individually.

Alternatively, a regex that should work would be...

/access_token=(.*?)(?:&expires=(.*))/
like image 162
Amber Avatar answered Sep 28 '22 10:09

Amber


If the format is strict, then you use this regex:

access_token=([^&]+)(?:&expires=(.*))?

Then access_token value is in \1, and expires, if there's any, will be in \2.

like image 30
polygenelubricants Avatar answered Sep 28 '22 09:09

polygenelubricants