Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript access to Location header's URL fragment for OAuth 2

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

like image 872
user1647398 Avatar asked Sep 04 '12 21:09

user1647398


People also ask

What is redirect URL in OAuth2?

redirected uri is the location where the user will be redirected after successfully login to your app.

What is OAuth callback URL?

A callback URL is the URL that is invoked after OAuth authorization for the consumer (connected app). In some contexts, the URL must be a real URL that the client's web browser is redirected to.


1 Answers

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'].

like image 178
Jan Gerlinger Avatar answered Oct 25 '22 03:10

Jan Gerlinger