Most clever way to parse a Facebook OAuth 2 access token string
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|TxQrqFKhiXm40VXVE1OB开发者_开发问答UtZc3Ks.
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!
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=(.*))/
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
.
Query string parsing usually involves these steps:
- If it is a complete URL, take the part after the first
?
- split the rest on
&
- for each of the resulting
name=value
pairs, split them on=
- URL-decode to the
value
and thename
(!) - stuff the result into a data structure of your liking
Using regex is possible, but makes invalid assumptions about the state of URL-encoding the string is in and fails if the order of the query string changes, which is perfectly allowed and therefore cannot be ruled out. Better to encapsulate the above in a little parsing function or use one of the existing URL-handling libraries of your platform.
精彩评论