6
votes

The OAuth 2.0 implicit grant (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.2) involves some interesting choreography between the client application, the browser and the authorization server. The auth server returns an HTTP 302 status code to the browser with a Location header like so:

Location: http://clientapp.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=example&expires_in=3600

The browser drops the fragment before it executes the redirection, and the service at clientapp.com/cb should respond with [from the spec] "a web page (typically an HTML document with an embedded script) capable of accessing the full redirection URI including the fragment retained by the user-agent, and extracting the access token (and other parameters) contained in the fragment".

I've implemented the authorization server portion of this, but have very little JavaScript experience. How do you get JavaScript to access the fragment that the browser stripped off before the redirection?

Thanks,
Michael

1

1 Answers

7
votes

Try something like this (taken from this german article):

<script>
   var fragmentString = location.hash.substr(1);
   var fragment = {};
   var fragmentItemStrings = fragmentString.split('&');
   for (var i in fragmentItemStrings) {
     var fragmentItem = fragmentItemStrings[i].split('=');
     if (fragmentItem.length !== 2) {
       continue;
     }
     fragment[fragmentItem[0]] = fragmentItem[1];
   }
</script>

Then you can reference your access token with fragment['access_token'].