AngularJS: Enable OWIN Refresh Tokens Using ASP.NET Web API 2

Introduction

In my previous article, we saw an overview of Token based authentication using ASP.NET web API and OWIN with the AngularJS application. In that post, we had created SPA (single page application) using AngularJS and authentication is done by using OWIN. This flow returns the authorization token and token will expire after certain time, after that user needs to login again. In this post, I will explain how can we alive the token long time using refresh token flow? With the refresh token the user does not need to login again and they use refresh token to request a new authorization token.

Here, idea of using refresh token is to issue short lived access token (around 20-30 minute) at the first time and then use refresh token to obtain new access token. In this idea user need to authenticate himself by providing user name and password and if the information provided by the client is valid, the response contains the short lived access token along with long lived refresh token. The refresh token is not access token but it is just identifier to the refresh token. Now after certain fixed time period, we can use this refresh token identifier and try to obtain another short lived access token. This new access token will use the further communication with server (Web API).

Using the refresh token to a Web API has several advantages:

  • The client does not required to hold the user name and password after the token has been generated i.e. the users do not required to re-enter their credentials for the lifetime of the token.
  • The back-end need not to validate password on every request.
  • The Credential validation is done at the authorization server.

Why are we not issuing long lived access token at the first place instead of adding this complexity

As we know, access tokens are self-descriptive; they contain all claims identity (user information) about the authenticated user once they are issued. Once the user obtaining the long lived token, s/he will be able to access the server resources as long as her/his token is not expire. There is no way to revoke access token unless we implement any custom logic which enforce us to store issued tokens in to the cache or database check with each request. With refresh tokens, a system can be revoked the access token by deleting the token from the cache or database and now Authorization Server will reject the request because the refresh token is no longer available. Refresh token allows us to ask the user name and password to user once for the authentication first time and then Authorization server can issue long lived refresh token and user will stay logged in all this period unless refresh token is not revoked.

Refresh token

Refresh tokens must bound with the client. Client is identity and with help of the client, application is attempting to communicate with the server (back-end API). Every client should have the client id and secret and usually Client Id/Secret is hard coded and it validates at the time of login.

Normally client id is unique public identifiers of our application when other application also use same web API. So this means that we need to authenticate our client first.

My post "Token Based Authentication Using ASP.Net Web API, OWIN and Identity " (step -5) explained, how we can configure the OAuth Authorization Server. ValidateClientAuthentication method is used to validate client credentials and make the client ID available in the pipeline for later processing. GrantResourceOwnerCredentials method is a method where we actual validate the user credential and generate the token.

Here we need to add one more method to the authorization server provider called "GrantRefreshToken". This method is called when refresh token request comes in. In this method, first we need to validate the client and we have chance to modify the outgoing access token and user claims.

  1. public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)  
  2. {  
  3.     //validate your client  
  4.     //var currentClient = context.ClientId;  
  5.   
  6.     //if (Client does not match)  
  7.     //{  
  8.     //    context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");  
  9.     //    return Task.FromResult<object>(null);  
  10.     //}  
  11.   
  12.     // Change authentication ticket for refresh token requests  
  13.     var newIdentity = new ClaimsIdentity(context.Ticket.Identity);  
  14.     newIdentity.AddClaim(new Claim("newClaim""newValue"));  
  15.   
  16.     var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);  
  17.     context.Validated(newTicket);  
  18.   
  19.     return Task.FromResult<object>(null);  
  20. }  
To refresh the token, first we need to add new class called "RefreshTokenProvider" which implements the interface “IAuthenticationTokenProvider”.

Here we need to create a secure handle to the refresh token and need to store data which associate the authentication ticket. In this article I have used Concurrent Dictionary to store generated refresh token and authentication ticket data.

So, Refresh Token class definition becomes as the following:
  1. using Microsoft.Owin.Security;  
  2. using Microsoft.Owin.Security.Infrastructure;  
  3. using System;  
  4. using System.Collections.Concurrent;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace WebAPI  
  8. {  
  9.     public class RefreshTokenProvider : IAuthenticationTokenProvider  
  10.     {  
  11.         private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();  
  12.         public async Task CreateAsync(AuthenticationTokenCreateContext context)  
  13.         {  
  14.             var guid = Guid.NewGuid().ToString();  
  15.   
  16.             // copy all properties and set the desired lifetime of refresh token  
  17.             var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)  
  18.             {  
  19.                 IssuedUtc = context.Ticket.Properties.IssuedUtc,  
  20.                 ExpiresUtc = DateTime.UtcNow.AddMinutes(60)//DateTime.UtcNow.AddYears(1)  
  21.             };  
  22.             var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);  
  23.   
  24.             _refreshTokens.TryAdd(guid, refreshTokenTicket);  
  25.   
  26.             // consider storing only the hash of the handle  
  27.             context.SetToken(guid);  
  28.         }  
  29.   
  30.         public void Create(AuthenticationTokenCreateContext context)  
  31.         {  
  32.             throw new NotImplementedException();  
  33.         }  
  34.   
  35.         public void Receive(AuthenticationTokenReceiveContext context)  
  36.         {  
  37.             throw new NotImplementedException();  
  38.         }  
  39.   
  40.         public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)  
  41.         {  
  42.             AuthenticationTicket ticket;  
  43.             string header = context.OwinContext.Request.Headers["Authorization"];  
  44.   
  45.             if (_refreshTokens.TryRemove(context.Token, out ticket))  
  46.             {  
  47.                 context.SetTicket(ticket);  
  48.             }  
  49.         }  
  50.     }  
  51. }  
We need to add our refresh token generation logic inside the "CreateAsync" method. The following are some important implementation point of this method. 
  • Here, we are using a unique identifier for the refresh token. Guid is enough for generating the refresh token key. We can use any other strong algorithm to generate refresh token key.

  • After that we are generating refresh token properties by reading context ticket properties and set it’s expiry time.

  • After adding all context properties, we are generating refresh token authentication ticket and adding it to the Concurrent Dictionary.

  • Finally, call the context.SetToken method.

Now we need to register the token provider in the starting.

  1. OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()  
  2. {  
  3.   
  4.     AllowInsecureHttp = true,  
  5.     TokenEndpointPath = new PathString("/token"),  
  6.     AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),  
  7.     Provider = new AuthorizationServerProvider(),  
  8.     RefreshTokenProvider = new RefreshTokenProvider()  
  9. };  
Refresh Token example with AngularJS

In this post, I have used same example which was used in my previous post. Once above described code is completed, we will obtain refresh token along with the access token. Now, this generated refresh token need to be stored somewhere in client side memory, either the client window session or local storage.

Refresh Token example with AngularJS

In this example, we obtain the refresh token and store it in user info object on windows session. So some changes are required in login method and the definition of login method becomes the following: 

Login” method in loginservice.js file:
  1. this.login = function (userName, password) {  
  2.     deferred = $q.defer();  
  3.     var data = "grant_type=password&username=" + userName + "&password=" + password;  
  4.     $http.post(loginServiceURL, data, {  
  5.         headers:  
  6.             { 'Content-Type''application/x-www-form-urlencoded' }  
  7.     }).success(function (response) {  
  8.         var o = response;  
  9.         userInfo = {  
  10.             accessToken: response.access_token,  
  11.             userName: response.userName,  
  12.             refreshToken: response.refresh_token  
  13.         };  
  14.         authenticationService.setTokenInfo(userInfo);  
  15.         authData.authenticationData.IsAuthenticated = true;  
  16.         authData.authenticationData.userName = response.userName;  
  17.         deferred.resolve(null);  
  18.     })  
  19.     .error(function (err, status) {  
  20.         authData.authenticationData.IsAuthenticated = false;  
  21.         authData.authenticationData.userName = "";  
  22.         deferred.resolve(err);  
  23.     });  
  24.     return deferred.promise;  
  25. }  
When we made refresh token request, we need to set "grant_type" to "refresh_token" and must pass refresh token key and client id if any with the request. If all went successfully, we will receive new access token and new refresh token key.

To check and validate refresh token code I have made the following changes in my code. 
  1. Add one link called “Refresh Token” in Index.html.
    1. <li data-ng-hide="!authentication.IsAuthenticated"><a href="" data-ng-click="refreshToken()">Refresh Token</a></li>  
  2. Add the following function to AuthenticationService.js. This method is used to refresh the token.
    1. this.refreshToken = function() {  
    2.     var loginServiceURL = serviceBase + 'token';  
    3.     var deferred = $q.defer();  
    4.     var token = this.getTokenInfo();  
    5.     var data = "grant_type=refresh_token&refresh_token=" + token.refreshToken + "&client_id=";  
    6.   
    7.     $http.post(loginServiceURL, data).success(function (response) {  
    8.         var o = response;  
    9.         var userInfo = {  
    10.             accessToken: response.access_token,  
    11.             userName: response.userName,  
    12.             refreshToken: response.refresh_token  
    13.         };  
    14.         AuthenticationService.setTokenInfo(userInfo);  
    15.         AuthenticationService.setHeader($http);  
    16.         hasHttpRequest = false;  
    17.         deferred.resolve(null);  
    18.     }).error(function (err, status) {  
    19.         deferred.resolve(err);  
    20.     });  
    21.     return deferred.promise;  
    22. }  
  3. Add refresh token method to indexController.js.
    1. (function () {  
    2.   
    3.     'use strict';  
    4.     app.controller('indexController', ['$scope''$location''authData''LoginService''AuthenticationService', function ($scope, $location, authData, loginService, authenticationService) {  
    5.   
    6.         $scope.logOut = function () {  
    7.             loginService.logOut();  
    8.             $location.path('/home');  
    9.         }  
    10.         $scope.authentication = authData.authenticationData;  
    11.   
    12.         $scope.refreshToken = function () {  
    13.             authenticationService.refreshToken();  
    14.         }  
    15.   
    16.   
    17.     }]);  
    18. })();  

Output:

refresh token


Output

Summary

Hopefully this post is useful for implementing refresh token. Here I have called refresh token method manually (by clicking the link button) but it should be automated i.e. it should be called after specific time period just before expire access token.


Similar Articles