You thought identity management is ‘done’? Think twice: thinktecture IdentityServer v2 Beta is here
Test post

OAuth2 in thinktecture IdentityServer v2: Implicit Grant Flow with JavaScript

Our thinktecture IdentityServer version 2 will be a very different and very powerful identity beast!

Dominick already talked quite a bit about the features and how to use them. And Brock is surely at it as well.

Today I will show how to use IdentityServerv2 to implement the OAuth2.0 implicit grant flow as outlined in the official OAuth2 spec – and we are going to use a JavaScript client for that.

For the sake of a little bit of mobile-ness I am going to use KendoUI Mobile to have a native looking mobile UI (which you could then combine e.g. with Cordova/PhoneGap to create a native app).

We are going to look to secure a super novel and world overtaking… TODO app Smile


Admittedly, this is only the basic gist of what an app should look like and feature-wise we will focus on the OAuth part today.
First let’s head to IdentityServer an create a new OAuth Client like this:


One important part of the configuration is the callback/redirect URI. This is where the IdP sends us the token to.

In addition, we need a relying party/resource we can use to create tokens for and which will accept these tokens coming from our JavaScript clients.


Alright, time to jump on to the client side.
I try to encapsulate my JS code as much as possible. One nice pattern to get a basic structure is MVVM and KendoUI has good support for that.

The page above for the Start tab has a viewmodel which does just fire up the OAuth process (in this case the authentication):

   1:  var startViewModel = kendo.observable({
   2:      openLoginView: function () {
   3:          oauth2ViewModel.openAuthWindow(
   4:             endpoints.IdpOauthEndpointUrl);
   5:      }
   6:  });

The OAuth viewmodel holds the token and offer methods to kick off the login process and parse the token from the return URL.

   1:  var oauth2ViewModel = kendo.observable({
   2:      token: "",
   4:      openAuthWindow: function () {
   5:          var url = endpoints.IdpOauthEndpointUrl + "?" 
   6:             + $.param(oAuthConfig);
   7:, "Login", "height=500,width=350");
   8:      },
  10:      loginCallback: function (params) {
  11:          this.token = params["access_token"];
  12:          window.kendoMobileApplication.navigate("#todosPage");
  13:      }
  14:  });

In order to craft the correct URL for IdentityServer we need a couple of parameters which need to correspond to what we previously set up in IdSrv for the OAuth client and the RP (see the IdSrv screenshots above):

   1:  var endpoints = {
   2:      IdpOauthEndpointUrl: "https://localhost/idsrv/issue/
   3:         oauth2/authorize"
   4:  };
   6:  var oAuthConfig = {
   7:      client_id: "tt_tudus",
   8:      scope: "",
   9:      response_type: "token",
  10:      redirect_uri: "http://localhost/simpletudus/
  11:         oauthcallback.html"
  12:  }

Alright. Let’s look at the flow now.
Once we clicked on Login a new window pops up which loads the IdentityServer login page:


After loging into IdSrv we get the resource consent page and choose to allow access:


IdSrv will now send the token to callback URL specified earlier in the IdSrv config.

This URL looks something like this:


The code of the oauthcallback.html page is pretty simple. It parses the token from the hash (#) part of the URL and fires an event on the calling page to pass over the token (see the Google OAuth developers page for more details on the process):

   1:  <script src="js/libs/jquery-1.7.1.min.js" type="text/javascript"></script>
   2:  <script src="js/libs/" type="text/javascript"></script>
   4:  <script type="text/javascript">
   5:      //var params = {}, queryString = location.hash.substring(1),
   6:      //    regex = /([^&=]+)=([^&]*)/g, m;
   8:      //while (m = regex.exec(queryString)) {
   9:      //    params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  10:      //}
  12:      var params = $.deparam.fragment(
  13:         location.hash.substring(1));
  15:      window.opener.oAuthCallback(params);
  16:      window.close();    
  17:  </script>

: I am using jQuery BBQ in the above code to parse the URL, the commented code shows how to do it without any external library.

In the main page we have some kind of a proxy event handler which just passes the token on to the above shown OAuth viewmodel:

   1:  <script>
   2:      function oAuthCallback(params) {
   3:          oauth2ViewModel.loginCallback(params);
   4:      }
   5:  </script>

In the OAuth viewmodel login callback method we then simply set the token and trigger navigation to the TODO items page.

When hitting the refresh button in the upper left side of the Items view the actual call to the resource is made with standard jQuery. This happens in the loadTodos call:

   1:  var todosViewModel = kendo.observable({
   2:      todosSource: new
   3:         { sort: { field: "title", dir: "asc" } }),
   5:      loadTodos: function () {
   6:          var self = this;
   8:          dataservices.getTodos(oauth2ViewModel.token)
   9:              .done(function (data) {
  10:        ;
  11:              });
  12:      }
  13:  });

The data services logic is embedded in its own ‘class’ and simply uses the token acquired before to set the appropriate Bearer Authorization header before making the jQuery GET request against the TODO items resource (which is implemented with ASP.NET Web API, BTW):…

   1:  var dataservices = (function () {
   2:      function beforeSend(xhr, token) {
   3:          xhr.setRequestHeader("Authorization", 
   4:             createBearerHeader(token));
   5:      }
   7:      function createBearerHeader(token) {
   8:          var header = "Bearer " + token;
   9:          return header;
  10:      }
  12:      return {
  13:          getTodos: function (token) {
  14:              return $.ajax({
  15:                  url: endpoints.ServiceEndpointUrl,
  16:                  type: "get",
  17:                  dataType: "json",
  18:                  beforeSend: function (xhr) { beforeSend(xhr, token); }
  19:              });
  20:          }
  21:      };
  22:  }());

And voila…:


So please head to GitHub and get the IdSrv bits and give us feedback – thanks!

The entire code for this complete end-to-end sample can be found on GitHub.

Hope this helps.


Feed You can follow this conversation by subscribing to the comment feed for this post.


I really appreciate the example since it helped clarify a few different concepts for me regarding creating a pure html PhoneGap-based mobile app and calling Identity Server with KendoUI.

One thing that may be worth nothing (since it tripped me up initially) is that while the above example works great out of the box with the debug version of Identity Server, if you install the released build I believe that in addition to your instructions above you will also need to log into Identity Server as an admin, go to Protocols, enable OAuth2 (since is only enabled in the debug version by default), and then click on the Protocols OAuth2 link that just appeared and enable Enable Implicit flow.

One question I did have, though: if one is very concerned about security because of the nature of their application would you consider this approach secure when Identity Server returns the access token to the callback url as a parameter?

And if not, is there a better approach you would recommend for a pure html/css/javascript/phonegap mobile app which is going to be calling web services to get their data?

Christian Weyer

Hi Chuck,

interesting points.
Could you be so kind and browse over to the IdSrv issues list and add a new issue:


Maximilian Alexander

I might be really confused, but in this flow, is there any possiblity to login through an external provider like the home realm discovery screen (i.e. using Google, Facebook, ADFS etc...)

Christian Weyer

Hi Maximilian,

can we please keep all questions & discussions on the GitHub repo's issue list? :)

Very nice! This app provides a great playground to get up and running with Identity Server.

Question - is it possible to set up this kind of client login via the other Identity Providers - like the Facebook, Google, or Live providers? Specifically, instead of hitting the ~/issue/oauth2/authorize url, could it hit the ~/issue/hrd url?

Christian Weyer

Hey - no, sorry. This is currently not possible.
Maybe we will consider this later... or you find some money to throw at us to do it sooner than later ;)

Nestor Reyes

Good example, but how would I trigger a logout?

Christian Weyer


can you please direct this question to the IdSrv forums?


Julien Morvan

Hi nice article but it seems like OAuth2 now doesnt allow non SSL callback url... How should I go about setting up my callback on a cordova app?


Awesome example Chris!

Few things to help other folks who encounter same problem I have.

For HTTPS, you can either turn it off in IdentityServer configuration (General configuration), or use self-signed SSL certificate in IIS.
If using SSL, make sure applicationConstants.js's oAuthConfig redirect_uri also use HTTPS. This must match your OAuth Clients setting in IdentityServer.
applicationConstants.js's endpoints IdpOauthEndpointUrl must match your IdentityServer URL.

Next thing is, the sample project 's web.config oauthSigningKey need to change. The key must match your Relying Party's Symmetric Signing Key.

Finally, SecurityConfig.cs in the sample project also need a little modification. The issuer parameter for AddJsonWebToken must match your issuer's Site ID. This can be seen in General Configuration of the Identity Server.


The comments to this entry are closed.