Darrel Miller: Where, oh where, does the API key go?

Yesterday on twitter I made a comment criticizing the practice of putting an API key in a query string parameter.  I was surprised by the amount of attention it got and there were a number of responses questioning the significance of my objection.  Rather than try and reply in 140 character chunks, I decided a blog post was in order.

Security

Most of the comments were security related,

It is true that whether the API key is put in the URL or in the Authorization header. They are both going to be sent over the wire in clear text.  If security is critical then HTTPS is going to be necessary and both approaches would be equivalent… over the wire. 

The security problem is not really when the message is going over the wire, it is what happens to it on the client and server.  We developers like writing things out to log files and URLs are full of useful information for debugging.

My friend Pedro pointed me to an article that demonstrates how API keys in URLs can become a major problem.

I'm not suggesting that by putting the API key into an authorization header, that all the problems go away.  It is just a matter of reducing the chances of sensitive information being stored in unsecured placed and then being misused.

It reminds me of the choice we make to lock our car doors.  Anyone who has locked their keys in the car knows how easy it is for someone with the right tools to get into a locked car. However, locking your doors does significantly reduce the chance of theft.

Andrew makes the suggestion to use the username:password convention was introduced in RFC1738 back in 1994.

When RFC 1738 was revised in 1998 and  became RFC 2396 the following text was added:

Some URL schemes use the format "user:password" in the userinfo field. This practice is NOT RECOMMENDED

In the latest revision of the URI specification, RFC3986, they went further,

Use of the format "user:password" in the userinfo field is deprecated.

The reasons for deprecating this feature are very much applicable to the use of API keys in the query string.  It is unfortunate that we aren't quicker at learning from the mistakes of those came before us.

Forget the security issue

When I wrote the tweet, I really wasn't complaining about having an API key in the URL for security reasons.  For me, there are a number of benefits of using the authorization header.

Consistency

One of constraints of REST is called the "Uniform Interface".  A benefit of this constraint is that when you start working with a new API, there should consistency with the way it works.  This helps to reduce the learning curve and it makes it easier to build re-usable code that depends on this consistency.

Many HTTP client libraries have the ability to set default headers that will automatically be sent with every request.  It's one line of code and you get to forget about API keys and focus on actually using the API.

When assigning an API key in a URL, you first need to know if the parameter is key, apikey, api-key or api_key. Then you need to modify the URL that you want to call to add the API key. Futzing around with strings to add a query parameter to an existing URL is full of annoying little gotchas.  It is not so hard to do on a case by case basic, but trying to write generic code that will work for any URI is just painful.

I'm quite sure that string manipulation of URLs is one of the primary reasons API providers create API specific client libraries to insulate client developers from these irritants.

Hypermedia

Another REST constraint is the hypermedia constraint.  I realize that hypermedia usage in the API world is still very exceptional, but it's popularity is growing.  Having to define a URI template for every embedded link, just to add an API key would be really annoying.

Caching

Believe it or not, Caching is another REST constraint Smile.  HTTP caches use the URL as part of the primary cache key, even the query string parameters.  If you add a API key into the URL you make it difficult to take advantage of HTTP caches for resources that are common to all users.  A cache would end up keeping a duplicate copy of the resource representation for every user.  Not only is this a waste of cache space, but it also reduces the cache hit ratio massively.

Self-Descriptive

It is interesting to note that if you use an Authorization header, HTTP caches have special logic that will prevent caching by public caches unless you specifically allow it using a cache-control directive.  When the API key is buried in a query string parameter, intermediaries have no idea that the representation has come from a protected resource and therefore don't realize that caching it might be a bad idea.  Using standard HTTP features, the way they were defined, allows intermediary components to perform useful functions because they can have a limited understanding of the message.

A Thousand paper cuts

I believe that the usability of an API is hugely impacted by many small factors that in isolation, seem fairly inconsequential.  It is the combined effect of these small issues that is significant.  There is also the impact of change.  What doesn't matter today, might be very significant sometime in the future. 

The HTTP specifications define a set of guidelines for building distributed applications that have been proven to work, in real running applications.  Disregarding the advice they contain is throwing money down the drain.

A final comment that I would like to address came from Bret,

My original objection was that using the Authorization was not an option in the API I was trying to use.  I understand why some users prefer to use query string parameters.  Providing an easy path to get users working with your product is critical and if providing them with a query string parameter to send the auth key helps that process then do it.  However, I also believe part of the role of API provider is to help educate API consumers on the best way to work with an API to get the best results over the long run.  Give them an easy way, and when they are ready, educate them on the better way.

Hopefully, this blog post has provided some concrete reasons as to why using an Authentication header is a better solution. 


Radenko Zec: Fixing issue with HTTPClient and ProtocolViolationException: The value of the date string in the header is invalid

When you parse a large number of sites / RSS feeds using Microsoft HTTPClient or WebClient you can get an exception :
”ProtocolViolationException: “The value of the date string in the header is invalid”

This error usually occurs when you try to access LastModified date in a response.

var  response  = (HttpWebResponse)httpRequest.GetResponse();
var lastModified = response.LastModified;

The problem is usually related where LastModified date is send in incorrect format that ignores the HTTP specs.

Then Microsoft code inside WebClient throws this exception.

This can be very painful but there is a nice workaround for this.

Instead of accessing strongly typed LastModified header property in response get it by reading it from the response header:

 var resultedLastModified = response.Headers["Last-Modified"];

After this you’ll need to check for nulls, and try to parse it as datetime but you will not get ugly “The value of the date string in the header is invalid” exception.

If you like this article don’t forget to subscribe to this blog and make sure you don’t miss new upcoming blog posts.

 

The post Fixing issue with HTTPClient and ProtocolViolationException: The value of the date string in the header is invalid appeared first on RadenkoZec blog.


Taiseer Joudeh: Secure ASP.NET Web API using API Key Authentication – HMAC Authentication

Web API Security

Recently I was working on securing ASP.NET Web API HTTP service that will be consumed by a large number of terminal devices installed securely in different physical locations, the main requirement was to authenticate calls originating from those terminal devices to the HTTP service and not worry about the users who are using it. So first thing came to my mind is to use one of the OAuth 2.0 flows which is Resource Owner Password Credentials Flow, but this flow doesn’t fit nicely in my case because the bearer access tokens issued should have expiry time as well they are non revocable by default, so issuing an access token with very long expiry time (i.e one year) is not the right way to do it.

After searching for couple of hours I found out that the right and maybe little bit complex way to implement this is to use HMAC Authentication (Hash-based Message Authentication Code).

The source code for this tutorial is available on GitHub.

What is HMAC Authentication?

It is a mechanism for calculating a message authentication code using a hash function in combination with a shared secret key between the two parties involved in sending and receiving the data (Front-end client and Back-end HTTP service) . The main use for HMAC to verify the integrity, authenticity, and the identity of the message sender.

So in simpler words the server provides the client with a public APP Id and shared secret key (API Key – shared only between server and client), this process happens only the first time when the client registers with the server.

After the client and server agrees on the API Key, the client creates a unique HMAC (hash) representing the request originated from it to the server. It does this by combining the request data and usually it will contain (Public APP Id, request URI, request content, HTTP method, time stamp, and nonce) in order to produce a unique hash by using the API Key. Then the client sends that hash to the server, along with all information it was going to send already in the request.

Once the server revives the request along with the hash from the client, it tries to reconstruct the hash by using the received request data from the client along with the API Key, once the hash is generated on the server, the server will be responsible to compare the hash sent by the client with the regenerated one, if they match then the server consider this request authentic and process it.

Flow of using API Key – HMAC Authentication:

Note: First of all the server should provide the client with a public (APP Id) and shared private secret (API Key), the client responsibility is to store the API Key securely and never share it with other parties.

Flow on the client side:

  1. Client should build a string by combining all the data that will be sent, this string contains the following parameters (APP Id, HTTP method, request URI, request time stamp, nonce, and Base 64 string representation of the request pay load).
  2. Note: Request time stamp is calculated using UNIX time (number of seconds since Jan. 1st 1970) to overcome any issues related to a different timezone between client and server. Nonce: is an arbitrary number/string used only once. More about this later.
  3. Client will hash this large string built in the first step using a hash algorithm such as (SHA256) and the API Key assigned to it, the result for this hash is a unique signature for this request.
  4. The signature will be sent in the Authorization header using a custom scheme such as”amx”. The data in the Authorization header will contain the APP Id, request time stamp, and nonce separated by colon ‘:’. The format for the Authorization header will be like: [Authorization: amx APPId:Signature:Nonce:Timestamp].
  5. Client send the request as usual along with the data generated in step 3 in the Authorization header.

Flow on the server side:

  1. Server receives all the data included in the request along with the Authorization header.
  2. Server extracts the values (APP Id, Signature, Nonce and Request Time stamp) from the Authorization header.
  3. Servers looks for the APP Id in a certain secure repository (DB, Configuration file, etc…) to get the API Key for this client.
  4. Assuming the server was able to look up this APP Id from the repository, it will be responsible to validate if this request is a replay request and reject it, so it will prevent the API from any replay attacks. This is why we’ve used a request time stamp along with nonce generated at the client, and both values have been included into HMAC signature generation. The server will depend on the nonce to check if it was used before within certain acceptable bounds, i.e. 5 minutes. More about this later.
  5. Server will rebuild a string containing the same data received in the request by adhering to the same parameters orders and encoding followed in the client application, usually this agreement is done up front between the client application and the back-end service and shared using proper documentation.
  6. Server will hash the string generated in previous step using the same hashing algorithm used by the client (SHA256) and the same API Key obtained from the secure repository for this client.
  7. The result of this hash function (signature) generated at the server will be compared to the signature sent by the client, if they are equal then server will consider this call authentic and process the request, otherwise the server will reject the request and returns HTTP status code 401 unauthorized.

Important note:

  • Client and server should generate the hash (signature) using the same hashing algorithm as well adhere to the same parameters order, any slight change including case sensitivity when implementing the hashing will result in totally different signature and all requests from the client to the server will get rejected. So be consistent and agree on how to generate the signature up front and in clear way.
  • This mechanism of authentication can work without TLS (HTTPS), as long as the client is not transferring any confidential data or transmitting the API Key. It is recommended to consume it over TLS. But if you can’t use TLS for any other reason you will be fine if you transmit data over HTTP.

Sounds complicated? Right? Let’s jump to the implementation to make this clear.

I’ll start by showing how to generate APP Id and strong 265 bits key which will act as our API Key, this usually will be done on the server and provided to the client using a secure mechanism (Secure admin server portal). There is nice post here explains why generating APP Ids and API Keys is more secure than issuing username and password.

Then I’ll build a simple console application which will act as the client application, lastly I’ll build HTTP service using ASP.NET Web API and protected using HMAC Authentication using the right filter “IAuthenticationFilter”, so let’s get started!

The source code for this tutorial is available on GitHub.

Section 1: Generating the Shared Private Key (API Key) and APP Id

As I stated before this should be done on the server and provided to the client prior the actual use, we’ll use symmetric key cryptographic algorithm to issue 256 bit key, the code will be as the below:

using (var cryptoProvider = new RNGCryptoServiceProvider())
	{
		byte[] secretKeyByteArray = new byte[32]; //256 bit
		cryptoProvider.GetBytes(secretKeyByteArray);
		var APIKey = Convert.ToBase64String(secretKeyByteArray);
	}

And for the APP Id you can generate a GUID, so for this tutorial let’s assume that our APPId is:

4d53bce03ec34c0a911182d4c228ee6c
  and our APIKey generated is: 
A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=
 and assume that our client application has received those 2 pieces of information using a secure channel.

Section 2: Building the Client Application

Step 1: Install Nuget Package
Add new empty solution named “WebApiHMACAuthentication” then add new console application named “HMACAuthentication.Client”, then install the below HTTPClient Nuget package which help us to issue HTTP requests.

Install-Package Microsoft.AspNet.WebApi.Client -Version 5.2.2

Step 2: Add POCO Model
We’ll issue HTTP POST request in order to demonstrate how we can include the request body in the signature, so we’ll add simple model named “Order”, add new class named “Order” and paste the code below:

public class Order
    {
        public int OrderID { get; set; }
        public string CustomerName { get; set; }
        public string ShipperCity { get; set; }
        public Boolean IsShipped { get; set; }
    }

Step 3: Call the back-end API using HTTPClient
Now we’ll use the HTTPClient library installed earlier to issue HTTP POST request to the API we’ll build in the next section, so open file “Program.cs” and paste the code below:

static void Main(string[] args)
        {
            RunAsync().Wait();
        }

        static async Task RunAsync()
        {

            Console.WriteLine("Calling the back-end API");

            string apiBaseAddress = "http://localhost:43326/";

            CustomDelegatingHandler customDelegatingHandler = new CustomDelegatingHandler();

            HttpClient client = HttpClientFactory.Create(customDelegatingHandler);

            var order = new Order { OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true };

            HttpResponseMessage response = await client.PostAsJsonAsync(apiBaseAddress + "api/orders", order);

            if (response.IsSuccessStatusCode)
            {
                string responseString = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseString);
                Console.WriteLine("HTTP Status: {0}, Reason {1}. Press ENTER to exit", response.StatusCode, response.ReasonPhrase);
            }
            else
            {
                Console.WriteLine("Failed to call the API. HTTP Status: {0}, Reason {1}", response.StatusCode, response.ReasonPhrase);
            }

            Console.ReadLine();
        }

What we implemented here is basic, we just issuing HTTP POST to the end point “/api/orders” including serialized order object, this end point is protected using HMAC Authentication (More about this later in post), and if the response status returned is 200 OK, then we are printing the response returned.

What worth nothing here that I’m using a custom delegation handler named “CustomDelegatingHandler”. This handler will help us to intercept the request before sending it so we can do the signing process and creating the signature there.

Step 4: Implement the HTTPClient Custom Handler
HTTPClient allows us to create custom message handler which get created and added to the request message handlers chain, the nice thing here that this handler will allow us to write out custom logic (logic needed to build the hash and set in the Authorization header before firing the request to the back-end API), so in the same file “Program.cs” add new class named “CustomDelegatingHandler” and paste the code below:

public class CustomDelegatingHandler : DelegatingHandler
        {
            //Obtained from the server earlier, APIKey MUST be stored securely and in App.Config
            private string APPId = "4d53bce03ec34c0a911182d4c228ee6c";
            private string APIKey = "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=";

            protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {

                HttpResponseMessage response = null;
                string requestContentBase64String = string.Empty;

                string requestUri = System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());

                string requestHttpMethod = request.Method.Method;

                //Calculate UNIX time
                DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
                TimeSpan timeSpan = DateTime.UtcNow - epochStart;
                string requestTimeStamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString();

                //create random nonce for each request
                string nonce = Guid.NewGuid().ToString("N");

                //Checking if the request contains body, usually will be null wiht HTTP GET and DELETE
                if (request.Content != null)
                {
                    byte[] content = await request.Content.ReadAsByteArrayAsync();
                    MD5 md5 = MD5.Create();
                    //Hashing the request body, any change in request body will result in different hash, we'll incure message integrity
                    byte[] requestContentHash = md5.ComputeHash(content);
                    requestContentBase64String = Convert.ToBase64String(requestContentHash);
                }

                //Creating the raw signature string
                string signatureRawData = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);

                var secretKeyByteArray = Convert.FromBase64String(APIKey);

                byte[] signature = Encoding.UTF8.GetBytes(signatureRawData);

                using (HMACSHA256 hmac = new HMACSHA256(secretKeyByteArray))
                {
                    byte[] signatureBytes = hmac.ComputeHash(signature);
                    string requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
                    //Setting the values in the Authorization header using custom scheme (amx)
                    request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}:{3}", APPId, requestSignatureBase64String, nonce, requestTimeStamp));
                }

                response = await base.SendAsync(request, cancellationToken);

                return response;
            }
        }

What we’ve implemented above is the following:

  • We’ve hard coded the APP Id and API Key values obtained earlier from the server, usually you need to store those values securely in app.config.
  • We’ve got the full request URI and safely Url Encoded it, so in case there is query strings sent with the request they will safely encoded, as well we’ve read the HTTP method used, in our case it will be POST.
  • We’ve calculated the time stamp for the request using UNIX timing (number of seconds since Jan. 1st 1970). This will help us to avoid any issues might happen if the client and the server resides in two different time zones.
  • We’ve generated a random nonce for this request, the client should adhere to this and should send a random string per method call.
  • We’ve checked if the request contains a body (it will contain a body if the request of type HTTP POST or PUT), if it contains a body; then we will md5 hash the body content then Base64 the array, we are doing this to insure the authenticity of the request and to make sure no one tampered with the request during the transmission (in case of transmitting it over HTTP).
  • We’ve built the signature raw data by concatenating the parameters (APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String) without any delimiters, this data will get hashed using HMACSHA256 algorithm.
  • Lastly we’ve applied the hashing algorithm using the API Key then base64 the result and combined the (APPId:requestSignatureBase64String:nonce:requestTimeStamp) using ‘:’ colon delimiter and set this combined string in the Authorization header for the request using a custom scheme named “amx”. Notice that the nonce and time stamp are included in creating the request signature as well they are sent as plain text values so they can be validated on the server to protect our API from replay attacks.

We are done of the client part, now let’s move to building the Web API which will be protected using HMAC Authentication.

Section 3: Building the back-end API

Step 1: Add the Web API Project
Add new Web application project named “HMACAuthentication.WebApi” to our existing solution “WebApiHMACAuthentication”, the template for the API will be as the image below (Web API core dependency checked) or you can use OWIN as we did in previous tutorials:

WebApiProject

Step 2: Add Orders Controller
We’ll add simple controller named “Orders” controller with 2 simple HTTP methods, as well we’ll add the same model “Order” we already added in the client application, so add new class named “OrdersController” and paste the code below, nothing special here, just basic Web API controller which is not protected and allows anonymous calls (we’ll protect it later in the post).

[RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
        [Route("")]
        public IHttpActionResult Get()
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var Name = ClaimsPrincipal.Current.Identity.Name;

            return Ok(Order.CreateOrders());
        }

        [Route("")]
        public IHttpActionResult Post(Order order)
        {
            return Ok(order);
        }

    }

    #region Helpers

    public class Order
    {
        public int OrderID { get; set; }
        public string CustomerName { get; set; }
        public string ShipperCity { get; set; }
        public Boolean IsShipped { get; set; }


        public static List<Order> CreateOrders()
        {
            List<Order> OrderList = new List<Order> 
            {
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };

            return OrderList;
        }
    }

    #endregion

Step 3: Build the HMAC Authentication Filter
We’ll add all our logic responsible for re-generating the signature on the Web API and comparing it with signature received by the client in an Authentication Filter. The authentication filter is available in Web API 2 and it should be used for any authentication purposes, in our case we will use this filter to write our custom logic which validates the authenticity of the signature received by the client. The nice thing about this filter that it run before any other filters especially the authorization filter, I’ll borrow the image below from a great article about ASP.NET Web API Security Filters by Badrinarayanan Lakshmiraghavan to give you better understanding on where the authentication filter resides.

ASP.NET Web API Security Filters
Now add new folder named “Filters” then add new class named “HMACAuthenticationAttribute” which inherits from “Attribute” and implements interface “IAuthenticationFilter”, then paste the code below:

public class HMACAuthenticationAttribute : Attribute, IAuthenticationFilter
    {
        private static Dictionary<string, string> allowedApps = new Dictionary<string, string>();
        private readonly UInt64 requestMaxAgeInSeconds = 300;  //5 mins
        private readonly string authenticationScheme = "amx";

        public HMACAuthenticationAttribute()
        {
            if (allowedApps.Count == 0)
            {
                allowedApps.Add("4d53bce03ec34c0a911182d4c228ee6c", "A93reRTUJHsCuQSHR+L3GxqOJyDmQpCgps102ciuabc=");
            }
        }

        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var req = context.Request;

            if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
            {
                var rawAuthzHeader = req.Headers.Authorization.Parameter;

                var autherizationHeaderArray = GetAutherizationHeaderValues(rawAuthzHeader);

                if (autherizationHeaderArray != null)
                {
                    var APPId = autherizationHeaderArray[0];
                    var incomingBase64Signature = autherizationHeaderArray[1];
                    var nonce = autherizationHeaderArray[2];
                    var requestTimeStamp = autherizationHeaderArray[3];

                    var isValid = isValidRequest(req, APPId, incomingBase64Signature, nonce, requestTimeStamp);

                    if (isValid.Result)
                    {
                        var currentPrincipal = new GenericPrincipal(new GenericIdentity(APPId), null);
                        context.Principal = currentPrincipal;
                    }
                    else
                    {
                        context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                    }
                }
                else
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
            }
            else
            {
                context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
            }

            return Task.FromResult(0);
        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            context.Result = new ResultWithChallenge(context.Result);
            return Task.FromResult(0);
        }

        public bool AllowMultiple
        {
            get { return false; }
        }

        private string[] GetAutherizationHeaderValues(string rawAuthzHeader)
        {

            var credArray = rawAuthzHeader.Split(':');

            if (credArray.Length == 4)
            {
                return credArray;
            }
            else
            {
                return null;
            }

        }
}

Basically what we’ve implemented is the following:

  • The class “HMACAuthenticationAttribute” derives from “Attribute” class so we can use it as filter attribute over our controllers or HTTP action methods.
  • The constructor for the class currently fill a dictionary named “allowedApps”, this is for the demo only, usually you will store the APP Id and API Key in a database along with other information about this client.
  • The method “AuthenticateAsync” is used to implement the core authentication logic of validating the incoming signature in the request
  • We make sure that the Authorization header is not empty and it contains scheme of type “amx”, then we read the Authorization header value and split its content based on the delimiter we’ve specified earlier in client ‘:’.
  • Lastly we are calling method “isValidRequest” where all the magic of reconstructing the signature and comparing it with the incoming signature happens. More about implementing this in step 5.
  • Incase the Authorization header is incorrect or the result of executing method “isValidRequest” returns false, we’ll consider the incoming request as unauthorized and we should return an authentication challenge to the response, this should be implemented in method “ChallengeAsync”, to do so lets implement the next step.

Step 4: Add authentication challenge to the response
To add authentication challenge to the unauthorized response copy and paste the code below in the same file “HMACAuthenticationAttribute.cs”, basically we’ll add “WWW-Authenticate” header to the response using our “amx” custom scheme . You can read more about the details of this implementation here.

public class ResultWithChallenge : IHttpActionResult
    {
        private readonly string authenticationScheme = "amx";
        private readonly IHttpActionResult next;

        public ResultWithChallenge(IHttpActionResult next)
        {
            this.next = next;
        }

        public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = await next.ExecuteAsync(cancellationToken);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(authenticationScheme));
            }

            return response;
        }
    }

Step 5: Implement the method “isValidRequest”.
The core implementation of reconstructing the request parameters and generating the signature on the server happens here, so let’s add the code then I’ll describe what this method is responsible for, open file “HMACAuthenticationAttribute.cs” again and paste the code below in class “HMACAuthenticationAttribute”:

private async Task<bool> isValidRequest(HttpRequestMessage req, string APPId, string incomingBase64Signature, string nonce, string requestTimeStamp)
        {
            string requestContentBase64String = "";
            string requestUri = HttpUtility.UrlEncode(req.RequestUri.AbsoluteUri.ToLower());
            string requestHttpMethod = req.Method.Method;

            if (!allowedApps.ContainsKey(APPId))
            {
                return false;
            }

            var sharedKey = allowedApps[APPId];

            if (isReplayRequest(nonce, requestTimeStamp))
            {
                return false;
            }

            byte[] hash = await ComputeHash(req.Content);

            if (hash != null)
            {
                requestContentBase64String = Convert.ToBase64String(hash);
            }

            string data = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);

            var secretKeyBytes = Convert.FromBase64String(sharedKey);

            byte[] signature = Encoding.UTF8.GetBytes(data);

            using (HMACSHA256 hmac = new HMACSHA256(secretKeyBytes))
            {
                byte[] signatureBytes = hmac.ComputeHash(signature);

                return (incomingBase64Signature.Equals(Convert.ToBase64String(signatureBytes), StringComparison.Ordinal));
            }

        }

        private bool isReplayRequest(string nonce, string requestTimeStamp)
        {
            if (System.Runtime.Caching.MemoryCache.Default.Contains(nonce))
            {
                return true;
            }

            DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);
            TimeSpan currentTs = DateTime.UtcNow - epochStart;

            var serverTotalSeconds = Convert.ToUInt64(currentTs.TotalSeconds);
            var requestTotalSeconds = Convert.ToUInt64(requestTimeStamp);

            if ((serverTotalSeconds - requestTotalSeconds) > requestMaxAgeInSeconds)
            {
                return true;
            }

            System.Runtime.Caching.MemoryCache.Default.Add(nonce, requestTimeStamp, DateTimeOffset.UtcNow.AddSeconds(requestMaxAgeInSeconds));

            return false;
        }

        private static async Task<byte[]> ComputeHash(HttpContent httpContent)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] hash = null;
                var content = await httpContent.ReadAsByteArrayAsync();
                if (content.Length != 0)
                {
                    hash = md5.ComputeHash(content);
                }
                return hash;
            }
        }

What we’ve implemented here is the below:

  • We’ve validated that public APPId received is registered in our system, if it is not we’ll return false and will return unauthorized response.
  • We’ve checked if the request received is a replay request, this means that checking if the nonce received by the client is used before, currently I’m storing all the nonce received by the client in Cache Memory for 5 minutes only, so for example if the client generated a nonce “abc1234″ and send it with a request, the server will check if this nonce is used before, if not it will store the nonce for 5 minutes, so any request coming with same nonce during the 5 minutes window will consider a replay attack, if the same nonce “abc1234″ is used after 5 minutes then this is fine and the request is not considered a replay attack.
  • But there might be an evil person that might try to re-post the same request using the same nonce after the 5 minutes window, so the request time stamp becomes handy here, the implementation is comparing the current server UNIX time with the request UNIX time from the client, if the request age is older than 5 minutes too then it is rejected and the the evil person has no possibility to fake the request time stamp and send fresher one because we’ve already included the request time stamp in the signature raw data, so any change on it will result into new signature and it will not match the client incoming signature.
  • Note: If your API is published on different nodes on web farm, then you can store those nonce using Microsoft Azure Cache or Redis server, do not store them in DB because you need fast rad access.
  • Last step is we’ve implemented is to md5 hash the request body content if it is available (POST, PUT methods), then we’ve built the signature raw data by concatenating the parameters (APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String) without any delimiters. It is a MUST that both parties use the same data format to produce the same signature, the data eventually will get hashed using the same hashing algorithm and API Key used by the client. If the incoming client signature equals the signature generated on the server then we’ll consider this request authentic and will process it.

Step 5: Secure the API End Points:
Final thing to do here is to attribute the protected end points or controllers with this new authentication filter attribute, so open controller “Orders” and add the attribute “HMACAuthentication” as the code below:

[HMACAuthentication]
    [RoutePrefix("api/Orders")]
    public class OrdersController : ApiController
    {
     //Controller implementation goes here
    }

 Conclusion:

  • In my opinion HMAC authentication is more complicated than OAuth 2.0 but in some situations you need to use it especially if you can’t use TLS, or when you are building HTTP service that will be consumed by terminals or devices which storing the API Key in it is fine.
  • I’ve read that OAuth 1.0a is very similar to this approach, I’m not an expert of this protocol and I’m not trying to reinvent the wheel, I want to build this without the use of any external library, so for anyone reading this and have experience with OAuth 1.0a please drop me a comment telling the differences/ similarities about this approach and OAuth 1.0a.

That’s all for now folks! Please drop me a comment if you have better way implementing this or you spotted something that could be done in a better way.

The source code for this tutorial is available on GitHub.

Follow me on Twitter @tjoudeh

References:

The post Secure ASP.NET Web API using API Key Authentication – HMAC Authentication appeared first on Bit of Technology.


Dominick Baier: The Future of AuthorizationServer

Now that IdentityServer v3 is almost done, it makes sense to “deprecate” some of the older projects. Especially all of the functionality of AuthorizationServer is completely replaced by the IdSrv3 feature set.

AuthorizationServer is actually a pretty small and compact code base, and a relatively complete implementation of OAuth2 including a simple authorization model based on clients, applications and scopes. Also there are no major bugs (that we know about) or feature gaps.

IOW – if you want to use AS, simply make it part of your own code base and feel free to change it at will. Check the wiki for documentation.

If somebody wants to take over the project, contact me.


Filed under: ASP.NET, AuthorizationServer, OAuth, WebAPI


Darrel Miller: Constructing URLs the easy way

When building client applications that need to connect to a HTTP API, sooner or later you are going to get involved in constructing a URL based on a API Root and some parameters.  Often enough when looking at client libraries I see lots of ugly string concatenation and conditional logic to account for empty parameter values and trailing slashes.  And there there is the issue of encoding.  Several years ago a IETF specification (RFC 6570) was released that described a templating system for URLs and I created a library that implements the specification.  Here is how you can use it to make constructing even the most crazy URLs as easy as pie.

templates

Path Parameters

The simplest example is where you have a base URI and you need to update a parameter in the URL path segment,

[Fact]
public void UpdatePathParameter()
{
    var url = new UriTemplate("http://example.org/{tenant}/customers")
        .AddParameter("tenant", "acmé")
        .Resolve();

    Assert.Equal("http://example.org/acm%C3%A9/customers", url);
}

This is a really trivial case that could mostly be handled with a string replace.  However, a string replace wouldn’t take care of percent-encoding delimiters and unicode characters in the parameter value.

Under the covers there is a URITemplate class that can have parameters added to it and a Resolve method.  I have created a simple fluent inferface using extension methods to make it convenient quickly create and resolve a template..

Query Parameters

A slightly more complex example would be adding a query string parameter.

[Fact]
public void QueryParametersTheOldWay()
{
    var url = new UriTemplate("http://example.org/customers?active={activeflag}")
        .AddParameter("activeflag", "true")
        .Resolve();

    Assert.Equal("http://example.org/customers?active=true",url); 
}

This style of template can be problematic when there are optional query parameters and a parameter does not have a value.  A better way of defining query parameters is like this,

[Fact]
public void QueryParametersTheNewWay()
{
    var url = new UriTemplate("http://example.org/customers{?active}")
        .AddParameter("active", "true")
        .Resolve();

    Assert.Equal("http://example.org/customers?active=true", url);
}

when you don't want to provide any value at all, the template parameter will be removed.

[Fact]
public void QueryParametersTheNewWayWithoutValue()
{

    var url = new UriTemplate("http://example.org/customers{?active}")
        .AddParameters(null)
        .Resolve();

    Assert.Equal("http://example.org/customers", url);
}

In this last example I used a slightly different extension method that takes a single object and uses it's properties as key-value pairs.  This makes it easy to set multiple parameters.

[Fact]
public void ParametersFromAnObject()
{
    var url = new UriTemplate("http://example.org/{environment}/{version}/customers{?active,country}")
        .AddParameters(new
        {
            environment = "dev",
            version = "v2",
            active = "true",
            country = "CA"
        })
        .Resolve();

    Assert.Equal("http://example.org/dev/v2/customers?active=true&country=CA", url);
}

Lists and Dictionaries

Where URI Templates start to really shine as compared to simple string replaces and concatenation is when you start to use lists and dictionaries as parameter values. 

In the next example we use a list id values that are stored in an array to specify a property value.

[Fact]
public void ApplyParametersObjectWithAListofInts()
{
    var url = new UriTemplate("http://example.org/customers{?ids,order}")
        .AddParameters(new
        {
            order = "up",
            ids = new[] {21, 75, 21}
        })
        .Resolve();

    Assert.Equal("http://example.org/customers?ids=21,75,21&order=up", url);
}

We can use dictionaries to define both the query parameter name and value,

[Fact]
public void ApplyDictionaryToQueryParameters()
{
    var url = new UriTemplate("http://example.org/foo{?coords*}")
        .AddParameter("coords", new Dictionary<string, string>
        {
            {"x", "1"},
            {"y", "2"},
        })
        .Resolve();

    Assert.Equal("http://example.org/foo?x=1&y=2", url);
}

We can also use lists to define a set of path segments.

[Fact]
public void ApplyFoldersToPathFromStringNotUrl()
{

    var url = new UriTemplate("http://example.org{/folders*}{?filename}")
        .AddParameters(new
        {
            folders = new[] { "files", "customer", "project" },
            filename = "proposal.pdf"
        })
        .Resolve();

    Assert.Equal("http://example.org/files/customer/project?filename=proposal.pdf", url);
}

Parameters can be anywhere

Parameters are not limited to path segments and query parameters.  You can also put parameters in the host name.

[Fact]
public void ParametersFromAnObjectFromInvalidUrl()
{

    var url = new UriTemplate("http://{environment}.example.org/{version}/customers{?active,country}")
    .AddParameters(new
    {
        environment = "dev",
        version = "v2",
        active = "true",
        country = "CA"
    })
    .Resolve();

    Assert.Equal("http://dev.example.org/v2/customers?active=true&country=CA", url);
}

You can even replace the entire base URL.

[Fact]
public void ReplaceBaseAddress()
{

    var url = new UriTemplate("{+baseUrl}api/customer/{id}")
        .AddParameters(new
        {
            baseUrl = "http://example.org/",
            id = "22"
        })
        .Resolve();

    Assert.Equal("http://example.org/api/customer/22", url);
}

However, by default URI template will escape all delimiter characters in parameters, so the slashes in the base address would come out percent-encoded.  By adding the + operator to the front of the baseUrl parameter we can instruct the resolution algorithm to not escape characters in the parameter value.

Partial Resolution

A recently added feature to the library is the ability to only resolve parameters that have been passed and leave the other parameters untouched.  This is useful sometimes when you want to resolve base address and version parameters on application startup, but then want to add other parameters later.

[Fact]
public void PartiallyParametersFromAnObjectFromInvalidUrl()
{

    var url = new UriTemplate("http://{environment}.example.org/{version}/customers{?active,country}",resolvePartially:true)
    .AddParameters(new
    {
        environment = "dev",
        version = "v2"
    })
    .Resolve();

    Assert.Equal("http://dev.example.org/v2/customers{?active,country}", url);
}

And there is so much more…

The URI Template specification contains many more syntax options that I have not covered.  Many of them you may never use.  However, it is nice to know that if you ever run into some API that uses some strange formatting, there is a reasonable chance that URI templates can support it.

Although the templating language is fairly sophisticated, it was specifically designed to be fast to process.  The resolution algorithm can be performed by walking the template characters just once and performing substitutions along the way.

Where to find it

All the source code for the project can be found on Github and there is a nuget package available.  The library is built to support .Net35, .Net45 and there is a portable version that supports Win Phone 8, 8.1, WinRT and mono on Android and iOS.

Image Credit: Templates https://flic.kr/p/5Xc9sq


Taiseer Joudeh: AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL)

In my previous post Secure ASP.NET Web API 2 using Azure Active Directory I’ve covered how to protect Web API end points using bearer tokens issued by Azure Active Directory, and how to build a desktop application which acts as a Client. This Client gets the access token from the Authorization Server (Azure Active Directory) then use this bearer access token to call a protected resource exits in our Resource Server (ASP.NET Web API).

Azure Active Directory Web Api

Initially I was looking to build the client application by using AngularJS (SPA) but I failed to do so because at the time of writing the previous post Azure Active Directory Authentication Library (ADAL) didn’t support OAuth 2.0 Implicit Grant which is the right OAuth grant that should be used when building applications running in browsers.

The live AngularJS demo application is hosted on Azure (User: ADAL@taiseerjoudeharamex.onmicrosoft.com/ Pass: AngularJS!!), the source code for this tutorial on GitHub.

So I had discussion with Vittorio Bertocci and Attila Hajdrik on twitter about this limitation in ADAL and Vittorio promised that this feature is coming soon, and yes ADAL now supports OAuth 2.0 Implicit Grant and integrating it with your AngularJS is very simple, I recommend you to watch Vittorio video introduction on Channel 9 before digging into this tutorial.

AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL)

What is OAuth 2.0 Implicit Grant?

In simple words the implicit grant is optimized for public clients (can not store secrets) and those clients are built using JavaScript and they run in browsers. There is no client authentication happening here and the only factors should be presented to obtain an access token is the resource owner credentials and pre-registration for the redirection URI with the Authorization server. This redirect URI will be used to receive the access token issued by the Authorization server in a form of URI fragment.

What we’ll build in this tutorial?

In this tutorial we’ll build simple SPA application using AngularJS along with ADAL for JS which provides a very comprehensive abstraction for the Implicit Grant we described earlier. This SPA will communicate with a protected Resource Server (Web API) to get list of orders, and will request the access token from our Authorization Server (Azure Active Directory).

In order to follow along with this tutorial I’ve created a sample skeleton project which contains the basic code needed to run our AngularJS application and the Web API without adding any feature related to the security. So I recommend you to download it first so you can follow along with the steps below.

The NuGet packages I used in this project are:

Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Security.ActiveDirectory -Version 3.0.0

Step 1: Register the Web API into Azure Active Directory

Open Azure Management Portal in order to register our Web API as an application in our Azure Active Directory, to do so and after your successful login to Azure Management Portal, click on “Active Directory” in the left hand navigation menu, choose your active directory tenant you want to register your Web API with, then select the “Applications” tab, then click on the add icon at bottom of the page. Once the modal window shows as the image below select “Add an application my organization is developing”.
Azure New App
Then a wizard of 2 steps will show up asking you to select the type of the app you want to add, in our case we are currently adding a Web API so select “Web Application and/or Web API”, then provide a name for the application, in my case I’ll call it “AngularJSAuthADAL”, then click next.
Azure App Name
In the second step as the image below we need to fill two things, the Sign-On URL which is usually will be your base URL for your Web API, so in my case it will be “http://localhost:10966″, and the second field APP ID URI will usually be filled with a URI that Azure AD can use for this app, it usually take the form of “http://<your_AD_tenant_name>/<your_app_friendly_name>” so we will replace this with the correct values for my app and will be filed as “http://taiseerjoudeharamex.onmicrosoft.com/AngularJSAuthADAL” then click OK.

Azure App Properties

Step 2: Enable Implicit Grant for the Application

After our Web API has been added to Azure Active Directory apps, we need enable the implicit grant. To do so we need to change our Web API configuring using the application manifest. Basically the application manifest is a JSON file that represents our application identity configuration.

So as the image below and after you navigate to the app we’ve added click on “Manage Manifest” icon at the bottom of the page, then click on “Download Manifest”.

Download Manifest

Open the downloaded JSON application manifest file and change the value of “oauth2AllowImplicitFlow” node to “true“.  As well notice how the “replyUrls” array contains the URL which we want the token response returned to. You can read more about Web API configuration here.

After we apply this change, save the application manifest file locally then upload it again to your app using the “Upload Manifest” feature.

Step 3: Configure Web API to Accept Bearer Tokens Issued by Azure AD

Now and if you have downloaded the skeleton project right click on it and click on build to download the needed Nuget packages, if you want you can run the application and a nice SPA will be show up and the orders will be displayed as the image below because we didn’t configure the security part yet.

AngularJS Adal

Now open file “Startup.cs” and paste the code below:

public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
               new WindowsAzureActiveDirectoryBearerAuthenticationOptions
               {
                   Audience = ConfigurationManager.AppSettings["ida:ClientID"],
                   Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
               });
        }

Basically what we’ve implemented here is simple, we’ve configured the Web API authentication middleware to use “Windows Azure Active Directory Bearer Tokens” for the specified Active Directory “Tenant” and “Audience” (Client Id). Now any API controller lives in this API and attribute with [Authorize] attribute will only accept bearer tokens issued from this specified Active Directory Tenant, any other form of tokens will be rejected.

It is a good practice to store the values for your Audience, Tenant, Secrets, etc… in a configuration file and not to hard-code them, so open the web.config file and add 2 new “appSettings” as the snippet below, the value for the Client Id can be read your Azure App settings.

<appSettings>
    <add key="ida:Tenant" value="taiseerjoudeharamex.onmicrosoft.com" />
    <add key="ida:ClientID" value="1725911b-ad8f-4295-8258-cf95ba9f7ea6" />
  </appSettings>

Step 4: Protect Orders Controller

Now open file “OrdersController” and attribute it with [Authorize] attribute, by doing this any GET request to the path “http://localhost:port/api/orders” will return status code 401 if no token provided in the Authorization header. When you apply this the orders view won’t return any data until we obtain a valid token. Orders controller code will look as the below snippet:

[Authorize]
[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
	//Rest of code is here
}

Step 5: Download ADAL JavaScript Library

Now it is time to download and use ADAL JS library which will facilitates the AngularJS authentication using the Implicit grant, so after you download the file, open page “Index.html” and add reference to it at the end of the file as the code below:

<!-- 3rd party libraries -->
 <!Other JS references here -->
 <script src="scripts/adal.js"></script>

Step 6: Configure our AngularJS bootstrap file (app.js)

Now open file “app.js” where we’ll inject the ADAL dependencies into our AngularJS module “AngularAuthApp”, so after you open the file change the code in it as the below:

var app = angular.module('AngularAuthApp', ['ngRoute', 'AdalAngular']);

app.config(['$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', function ($routeProvider, $httpProvider, adalAuthenticationServiceProvider) {

    $routeProvider.when("/home", {
        controller: "homeController",
        templateUrl: "/app/views/home.html"
    });

    $routeProvider.when("/orders", {
        controller: "ordersController",
        templateUrl: "/app/views/orders.html",
        requireADLogin: true
    });

    $routeProvider.when("/userclaims", {
        templateUrl: "/app/views/userclaims.html",
        requireADLogin: true
    });

    $routeProvider.otherwise({ redirectTo: "/home" });

    adalAuthenticationServiceProvider.init(
      {
          tenant: 'taiseerjoudeharamex.onmicrosoft.com',
          clientId: '1725911b-ad8f-4295-8258-cf95ba9f7ea6'
      }, $httpProvider);

}]);
var serviceBase = 'http://localhost:10966/';
app.constant('ngAuthSettings', {
    apiServiceBaseUri: serviceBase
});

What we’ve implemented is the below:

  • We’ve injected the “AdalAngular” to our module “AngularAuthApp”.
  • The service “adalAuthenticationServiceProvider” is now available and injected into our App configuration.
  • We’ve set the property “requireADLogin” to “true” for any partial view requires authentication, by doing this if the user requested a protected view, a redirection to Azure AD tenant will take place and the user (resource owner) will be able to enter his AD credentials to authenticate.
  • Lastly, we’ve set the “tenant” and “clientId” values related to our AD Application.

Step 7: Add explicit Login and Logout feature to the SPA

The ADAL Js library provide us with explicit way to login/logout the user by calling “login” function, so to add this open file named “indexController.js” and replace the code existing with the code below:

'use strict';
app.controller('indexController', ['$scope', 'adalAuthenticationService', '$location', function ($scope, adalAuthenticationService, $location) {

    $scope.logOut = function () {
      
        adalAuthenticationService.logOut();
    }

    $scope.LogIn = function () {

        adalAuthenticationService.login();
    }

}]);

Step 8: Hide/Show links based on Authentication Status

For better user experience it will be nice if we hide the login link from the top menu when the user is already logged in, and to hide the logout link when the user is not logged in yet, to do so open file “index.html” and replace the menu items with code snippet below:

<div class="collapse navbar-collapse" data-collapse="!navbarExpanded">
                <ul class="nav navbar-nav navbar-right">
                    <li data-ng-hide="!userInfo.isAuthenticated"><a href="#">Welcome {{userInfo.profile.given_name}}</a></li>
                    <li><a href="#/orders">View Orders</a></li>
                    <li data-ng-hide="!userInfo.isAuthenticated"><a href="" data-ng-click="logOut()">Logout</a></li>
                    <li data-ng-hide="userInfo.isAuthenticated"><a href="" data-ng-click="LogIn()">Login</a></li>
                </ul>
            </div>

Notice that we are depending on object named “userInfo” to read property named “isAuthenticated”, this object is set in the “$rootScope” in ADAL JS library so it is available globally in our AngularJS app.

By completing this step and if we tried to run the application and request the view “orders” or click on “login” link, we will be redirected to our Azure AD tenant to enter user credentials and have an access to the protected view, there is lot of abstraction happening here that needs to be clarified in the section below.

ADAL JavaScrip Flow

  • Once the anonymous user request protected view (view marked with requireADLogin = true ) or hit on login link explicitly, ADAL will trigger login directly as the code highlighted here.
  • The Login in ADAL library means building redirection URI to the configured Azure AD tenant we’ve defined in the “init” method in “app.js” file, the URI will contain random “state” and “nonce” to uniquely identify each request and prevent from any reply requests, as well the value for the “redirect_uri” is set the to current location of the page which should match the value we’ve defined once we registered the application, lastly the “response_type” is set to “id_token” so the authorization server should send back a JWT token contains claims about the user. The redirection URI will look as the below and code for building the redirection URI is highlighted here

https://login.windows.net/taiseerjoudeharamex.onmicrosoft.com/oauth2/authorize?response_type=id_token&client_id=1725911b-ad8f-4295-8258-cf95ba9f7ea6&redirect_uri=http%3A%2F%2Fngadal.azurewebsites.net%2F&state=9cce69d3-af36-4eb4-a882-4e9b7080e90d&x-client-SKU=Js&x-client-Ver=0.0.3&nonce=d4313f89-dc4f-4590-b7fd-9bbc2b340759

  • Now the Azure AD login page will show up for the user, then the user will be prompted to enter his AD credentials as the image blow, assuming he entered credentials correctly, a redirection will take place to the following URI containing the token as part of URI fragment not query string along with the same state and nonce specified by ADAL earlier.

https://ngadal.azurewebsites.net/#/id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiIxNzI1OTExYi1hZDhmLTQyOTUtODI1OC1jZjk1YmE5ZjdlYTYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8wODExZmIzMS05M2VkLTRmZWItYTAwOS1kNmUyN2RmYWMxN2IvIiwiaWF0IjoxNDE3NDgwMjc5LCJuYmYiOjE0MTc0ODAyNzksImV4cCI6MTQxNzQ4NDE3OSwidmVyIjoiMS4wIiwidGlkIjoiMDgxMWZiMzEtOTNlZC00ZmViLWEwMDktZDZlMjdkZmFjMTdiIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI2OTIyYTVlZi01YmMyLTRiYmEtYjI5Yy1kODc0YzQyYjg1OWQiLCJ1cG4iOiJIYW16YUB0YWlzZWVyam91ZGVoYXJhbWV4Lm9ubWljcm9zb2Z0LmNvbSIsInVuaXF1ZV9uYW1lIjoiSGFtemFAdGFpc2VlcmpvdWRlaGFyYW1leC5vbm1pY3Jvc29mdC5jb20iLCJzdWIiOiJxVWU4UUQ4SzdwOF9zTlI5WlhQYWcyOVFCeGZURlhKbTBaVzR0UDdYSEJNIiwiZmFtaWx5X25hbWUiOiJKb3VkZWgiLCJnaXZlbl9uYW1lIjoiSGFtemEiLCJub25jZSI6ImQ1NmEwNDJhLWQzM2YtNGYxYS05ZmYwLTFjMWE1ZDk3YzVmMSIsInB3ZF9leHAiOiI3NDMzNDg5IiwicHdkX3VybCI6Imh0dHBzOi8vcG9ydGFsLm1pY3Jvc29mdG9ubGluZS5jb20vQ2hhbmdlUGFzc3dvcmQuYXNweCJ9.efAp-95yMvhLu--8TfXYwozJsc09OTsB5bneH9bvGzko6uLZj0YloDTIrVtu_SU95hOBpFvma0FOeGmsqre6DBwaLTSJDD9wTYtqmoCGwpTy_cewpS78MJ9aR-IjWx5O6K8Nt90d4ujaco5T-o2EQ4ygPx5Z6vH-sLy8t9NDVER7HtlClhRwj2uDUF-kdihh7lv5w0U7TqHZUtLkBNL2l69yY5F0Jdj0q7m81gNps6nfqfa8aypgmztpPWDJAChvwsD5r58CyGVXPKSp_2CfK0kkWasP6fmLKKi5tGPvjg-wEb2j47UVIgO8v9xIkqg8RGqnZ1lboZKa2FlCs-Jnrw&state=6ac680d1-8b3b-452a-97d2-3deddb4016fc&session_state=2d48f965-e026-4c08-9d38-2cce49ee72cb

Azure AD Login

Note: You can extract the JSON Web token manually and debug it using JWT debugging tool to explore the claims inside it.

  • Now once ADAL JS library receives this call back, it will go and extract the token from the hash fragment, try to decode this token to get user profile and other claims from it (i.e. token expiry), then store the token along with decoded claims in HTML 5 local storage so the token will not vanish if you closed the browser or do full refresh (F5) for your AngularJS application, the implementation is very similar to what we’ve covered earlier in AngularJS authentication post.
  • To be able to access the protected API end points, we need to send the token in the “Authorization” header using bearer scheme, the ADAL JS provides an AngularJS interceptor which is responsible to add the Authorization header to each XHR request if there is token stored in the localStorage, these is very similar to the interceptor we’ve added before in our AngularJS Authentication post.
  • If the user decided to “logout” from the system, then ADAL JS clears all the stored data in the HTML 5 local storage, so no token stored locally, then it issue redirect to the URI: https://login.windows.net/{tenantid}/oauth2/logout which will be responsible to clear the clear any session cookies created by Azure AD tenant, but remember that logging out from the system will not invalidate your token, if you extracted the token manually then it will remain valid until it expires, usually after 1 hour of the issuing time.
  • ADAL JS provides a nice way to renew the token without using grant_type = refresh_token, it tries to renew the token silently by using a hidden iframe which communicates with Azure AD tenant asking for a new token if there is a valid session established by the AD tenant.

The live AngularJS demo application is hosted on Azure (ADAL@taiseerjoudeharamex.onmicrosoft.com/AngularJS!!), the source code for this tutorial on GitHub.

Conclusion

ADAL JS library really simplifies adding OAuth 2.0 Implicit grant to your SPA, it is still on developer preview release so testing it out and providing feedback will be great to enhance it.

If you have any comments or enhancement on this tutorial please drop me comment. Thanks for taking the time to read the post!

Follow me on Twitter @tjoudeh

References

The post AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL) appeared first on Bit of Technology.


Ali Kheyrollahi: Health Endpoint in API Design: slippery slope that it is

Level [C3]

Health Endpoint is a common practice in building APIs. Such an endpoint, unlike other resources of a REST API, instead of achieving a business activity, returns the status of the service and while it can gather and return some data, it is the HTTP status that defines whether the service is "Up or Down". These endpoints commonly go and check a bunch configurations and connectivity with the dependent services, and even make a few calls for a "Test Customer" to make sure business activity can be achieved.

There is something above that just doesn't feel right to me - and this post is an exercise to define what I mean by it. I will explain what are the problems with the Health API and I am going to suggest how to "fix" it.

What is the health of an API anyway? The server up and running and capable of returning the status 200? Server and all its dependencies running and returning 200? Server and all its dependencies running capable of returning 200 in a reasonable amount of time? API able to accomplish some business activity? Or API able to accomplish a certain activity for a test user? API able to accomplish all activities within reasonable time? API able to accomplish all activities with its 95% percentile falling within an agreed SLA?

A Service is a complex beast. While its complexity would be nowhere near a living organism, it is useful to draw a parallel with a living organism. I remember from my previous medical life that the definition of health - provided by none other than WHO - would go like this:

"Health is a state of complete physical, mental and social well-being and not merely the absence of disease or infirmity."
In other words, defining health of an organism is a complex and involved process requiring deep understanding of the organism and how it functions. [Well, we are lucky that we are only dealing with distributed systems and their services (or MicroServices if you like) and not living organisms.] For servies, instead of health, we define the Quality of Service as a quantitative measure of a service's health.

Quality Of Servie is normally a bunch of orthogonal SLAs each defining a measurement for one aspect of the service. In terms of monitoring, Availability of a service is the most important aspect of the service to guage and closely follow. Availability of the service cannot simply be measured by the amount of time the servers dedicated to a service have been up. Apart from being reachable, service needs to respond within acceptable time (Low Latency) and has to be able to achieve its business activity (Functional) - no point server being reachable and return 503 error within milliseconds. So the number of error responses (as a deviation from the baseline which can be normal validation and business rule errors) also come into play.

So the question is how can we, expose an endpoint inside a service that can aggregate all above facets and report the health of a service. Simple answer is we cannot and should not commit ourselves to do it. Why? Let's take some simple help from algebra.
API/Service maps an input domain to an output domain (codomain). Also availability is a function of the output domain.

A service (f) is basically a function that maps the input domain (I) to an output domain (O). So:
O = f(I)
The output domain is a set of all possible responses with their status codes and latencies. Availability (A) is a function (a) of the output domain since it has to aggregate errors, latencies, etc:
A = a(O)
So in other words:
A = a(f(I))
So in other words, A cannot be measured without I - which for a real service is a very large set. And also it needs all of f - not your subset bypass-authentication-use-test-customer method.

So one approach is to sit outside the service and only deal with the output domain in a sort of proxy or monitoring server logs. Netflix have done a ton of work on this and have open sourced it as Hysterix) and no wonder I have not heard anything about the magical Health Endpoint in there (now there is an alternative endpoint which I will explain later). But if you want to do it within the service you need all the input domain and not just your "Test Customer" to make assertions about the health of your service. And this kind of assertion is not just wrong, it is dangerous as I am going to explain.

First of all, gradually - especially as far as the ops are concerned - that green line on the dashboard that checks your endpoint becomes your availability. People get used to trust it and when things go wrong out there and customers jump and shout, you will not believe it for quite a while because your eye sees that green line and trusts it.

And guess what happens when you have such an incident? There will be a post-mortem meeting and all tie-and-suits will be there and they identify the root cause as the faulty health-check and you will be asked to go back and fix your Health Check endpoint. And then you start building more and more complexity into your endpoint. Your endpoint gets to know about each and every dependency, all their intricacies. And before your know it, you could build a complete application beside your main service. And you know what, you have to do it for each and every service, as they are all different.

So don't do it. Don't commit yourself to what you cannot achieve.

So is there no point in having a simplistic endpoint which tells us basic information about the status of the service? Of course there is. Such information are useful and many load balancers or web proxies require such an endpoint.

But first we need to make absolutely clear what the responsibility of such an endpoint is.

Canary Endpoint

A canary endpoint (the name is courtesy of Jamie Beaumont) is a simplistic endpoint which gathers connectivity status and latency of all dependencies of a service. It absolutely does not trigger any business activity, there is no "Test Customer" of any kind and is not a "Health Endpoint". If it is green, it does not mean your service is available. But if it is red (your canary is dead) then you definitely have a problem.



So how does a canary endpoint work? It basically checks connectivity with its immediate dependencies - including but not limited to:
  • External services
  • SQL Databases
  • NoSQL Stores
  • External distributed caches
  • Service brokers (Azure RabbitMQ, Service Bus)
A canary result contains name of the dependency, latency and the status code. If any of the results has non-success code, endpoint returns a non-success code. Status code returned is used by simple callers such as load balancers. Also in all cases, we return a payload which is aggregated canary result. Such results can be used to feed various charts and draw heuristics into significance of variability of the latencies.

You probably noticed that External Services appear in Italic i.e. it is a bit different. Reason is if an external service has a canary endpoint itself, instead of just a connectivity check, we call its canary endpoint and add its aggregated result to the result we are returning. So usually the entry point API will generate a cascade of canary chirps that will tell us how things are.

Implementation of the connectivity check is generally dependent on the underlying technology. For a Cache service, it suffices to Set a constant value and see it succeeding. For a SQL Database a SELECT 1; query is all that is needed. For an Azure Storage account, it would be enough to connect and get the list of tables. The point being here is that none of these are anywhere near a business activity, so that you could not - in the remotest sense - think that its success means your business is up and running.

So there you have it. Don't do health endpoints, do canary instead.

Canary Endpoint implementation

A canary endpoint normally gets implemented as an HTTP GET call which returns a collection of connectivity check metrics. You can abstract the logic of checking various dependencies in a library and allow API developers to implement the endpoint by just declaring the dependencies.

We are currently working on an implementation in ASOS (C# and ASP.NET Web API) and there is possibility of open sourcing it.

Security of the Canary Endpoint

I am in favour of securing Canary Endpoint with a constant API key - normally under SSL. This does not provide highest level of security but it is enough to make it much more difficult to break into. At the end of the day, a canay endpoint lists all internal dependencies, components and potentially technologies of a system that can be used by hackers to target components.

Performance impact of Canary Endpoint

Since canary endpoint does not trigger any business activity, its performance footprint should be minimal. However, since calling the canary endpoint generates a cascade of calls, it might not be wise to iterate through all canary endpoints and just call them every few seconds since deeper canary endpoints in a highly layered architecture get called multiple times in each round. 



Darrel Miller: Runscope: Notifications from the Traffic Inspector

Runscope provides a way to log HTTP traffic that passes between client and server and it also can also continuously monitor Web API’s to ensure they are functioning correctly.  When something goes wrong with the Web API you can be notified immediately.  However, out of the box, there isn’t a way to be notified if there a failure appears in the traffic log.  However, it can be done,  it just requires a little creativity.  This blog post shows how. 

Canary

The API to the rescue

The Runscope Traffic Inspector is where you can see all the requests that have been relayed by Runscope.  Requests that have failed, based on their status code or connectivity issue, are included in the Errors stream. 

image

We can create a Radar Test that looks in this Errors stream by making a request to the Runscope API.

image

Unfortunately, it’s not quite that simple.  Once an error is in the Errors stream, the Radar test would end up notifying us of an error every time it checked.  We need a way of asking if any requests have been added to the Errors stream since the last time we ran the test.

image

We can also use the API to look at the results of a test and determine when it was last run. 

image

We can use the started_at timestamp from the response body of the last test run to then query the errors stream for requests since that timestamp. 

image

There is the possibility that if requests happen between the time that the test starts and the time the errors collection is queried, that the error may be reported twice.  This seems like a better alternative than using the finished_at and risk missing an error than comes in whilst the test is running.

Accessing the API

In order to use the Runscope API we need an API Key.  We can get one of those by defining an Application within Runscope account configuration.

image

The Website URL and Callback URL are dummy values because your account is the only one who will access the API and therefore you don’t need to use OAuth2 web flow authentication.  Once you create the application you will find a Access Token at the bottom of the page.

image

We will now be able to use this access token in our tests.

Creating the Tests

Before creating the tests we should create a new Bucket to hold the tests.  I called this bucket “Traffic Tester”. By using a different bucket we can avoid getting the traffic relating to monitoring intermixed with our actual relayed traffic.  Make a note of the “Traffic Tester” bucket key which is displayed in the bottom left corner of the Traffic Inspector screen.

The next step is to go to the Radar view and create a test.  I created a test called “Monitor Slackbot Traffic” as I want to use it to notify me if there are any errors that occur in my Slackbot integration.

Identifying the Test itself

The first request that we add to this test is going to determine the last time that the test was run.  Before we can do this, we need to know the UUID of the test.  We can use the API to tell us this.  So initially, we are going to set up the first request to just determine the UUID.

Set the request URI to be

https://api.runscope.com/buckets/{TrafficTesterBucketKey}/radar

In my case the URI looked like this, your bucket key will be different,

image

You will also need to add a Authorization header that has a value that has this format,

bearer {APIKey}

My header looked something like this. 

image

Run this test and when it succeeds, check the Last Response value.  This JSON object is a description of our “Monitor Slackbot Traffic” test and it contains a UUID property to identify the test.  Copy that UUID value.

image

Getting the “Since” value

Change the URL of the test to be,

https://api.runscope.com/buckets/{TrafficTesterBucketKey}/radar/{TestUUID}/results

replacing both the bucket key {TrafficTesterBucketKey} and {TestUUID} values.  Next, add a Variable named since like this,

image

We get the started_at value of data[1] instead of data[0] because data[0] is the information about the currently running test.  We want to know when the last test started.

At this point you can try running the test and see if it populates the since variable with a timestamp value.

image

Time to Check the Errors Stream

Create the next request and set up the same Authorization header as the previous request.

Set the new request URL to be

https://api.runscope.com/buckets/{bucketToMonitor}/errors?since={{since}}

Replace {bucketToMonitor} with the bucket key of the bucket you wish to monitor!

When the request runs it will return a data array that either contains errors or does not.  I tried to use the standard assertions for this but could not find a way that could handle the empty array.  So instead, I used a bit of script code to do the check.

Add the following script code to the request to complete the request,

image

Tell somebody about it

Add some notifications to the test,

image

This will send you an email if any request gets captured in the Errors stream.  If you prefer to use some other notification method then select the Integrations page and select one of our many integration partners.

Is this useful to you?

Ideally, it shouldn’t require quite this much creativity to be able to do this.  Let me know if this is useful to you and we’ll find a  way of making it much simpler.

Image Credit: Canary https://flic.kr/p/c2fdZG


Darrel Miller: The Web API business layer anti-pattern

What follows is a description of an architectural pattern that I see many developers discussing that I believe is an anti-pattern.  My belief is based on architectural theory and I have no empirical evidence to back it up, so feel free to come to your own conclusions.

The proposed architecture looks like this,

image

I’ve never been a big fan of architecture diagrams like this, because they are a purely logically representation of the architecture and forget about physical realities.

Consider this next diagram which is an example of how this architecture might actually be deployed.

image

In this diagram I changed the colours of the arrows to indicate the protocol used to interact between the components. The blue arrows use HTTP, the purple one is an in-process call and the red one is cross process but most likely not using HTTP. 

HTTP is smart but not very quick

HTTP is designed to enable communication over high latency distributed networks.  It is a text based protocol that enables the transmission of a large amount of semantically rich information in a single request/response pair.  It was designed to scale massively and allow application components to evolve independently.  It was not designed to be particularly efficient over high speed connections within a data center.

High speed in the data center

HTTP is convenient, but definitely not the best choice when communicating with a database server within a data center. The interaction between the Web Site and the Web API is HTTP, because that’s the protocol of choice for Web APIs.  However,  I think it is important to question the wisdom of this interaction.

The right protocol for the right job

It is highly likely that the Web Site and the Web API are living in the same data center. It is quite possible that they are running on the same physical machine.  This means that interactions between the two do not even need a network round trip.  There are much faster ways for the web site to get access to the data it needs than using HTTP to talk to a Web API.

DRY Layers

However, from what I have heard, performance is not the motivating factor for funneling all interactions through the Web API.  The intent is to provide a single interface that all “client” applications can consume.  The goal is re-use.  The theory being that we can write a single Web API and all the different client applications can consume that single API. 

Building good APIs for clients that are communicating across the Internet, need to satisfy a different set of requirements, as compared to building an API for a client sitting across the room.  Internet APIs can’t afford to be chatty.  They tend to be more coarsely grained and contain more metadata in order to reduce chattiness.  They also need to be much more resilient to change.  It’s not hard to push an update to the Web Site when the Web API changes, but it is a lot more challenging to update mobile devices, or some third party integration.

It isn’t impossible, it’s just sub-optimal

You can share a Web API between both local and remote clients.  The problems you will encounter will depend on who is the driving force behind API changes.  If the Web Site requirements push API changes then you are likely to end up with something that works OK for the web site and sucks horribly for the remote clients.  If you are lucky, it will be the remote clients that drive the API and hopefully the performance advantages of being local will make up for the inefficient interface that the Web Site needs to deal with.

A better way

image

In my opinion, a better unit of re-use would be the business logic of the application packaged up with a package manager and then deployed into either the Web Site or Web API projects.  With this approach, the Web Site gets high speed access to the underlying business logic and data and the Web API gets to focus on optimizing for remote clients.

Feedback

As I started out saying, this opinion is based on theory.  I’d be really interested in hearing about practical experiences that developers have had with these types of scenarios.   Some readers might find this a stretch, but I see a correlation between what I am describing here and the changes that Neflix implemented to its internal architecture.

It is worth noting also that many of the negative impacts that I am envisioning are not necessarily going to surface in the first six months of the project.  I tend to focus on the long term evolution of an application, so if you happen to be building a tool for your internal HR department that is going to be scrapped next year, feel free to ignore everything I just said Smile.


Darrel Miller: Continuous Integration, Deployment and Testing of your Web APIs with AppVeyor and Runscope

Fast iterations can be very valuable to the software development process, but make for more time spent doing deployments and testing.  Also, more deployments means more opportunities to accidentally introduce breaking changes into your API. 

RubeGoldbergMachine

AppVeyor is a cloud based continuous integration server and Runscope enables you to do integration testing of your Web APIs, when these services are combined they can save you time doing the mechanical stuff and ensure your API consumers stay happy.

The following steps show the key points to achieve this integration using AppVeyor, Runscope and Azure websites.

1) Create your Web API solution.

image

2) Commit your source code to a publicly accessible source code repository in Github, BitBucket, Visual Studio Online or Kiln.

3) Setup a default AppVeyor project.

image

3b) If  you did not include your Nuget packages in source control then you will need to go to the “Settings –> Build” page and add the nuget restore command.

image

4) Create an Azure Web Site from the Azure management portal using the Quick Create option.   After the site has been created you should setup deployment credentials.

image

5) Return back to the AppVeyor project configuration and setup the deployment of the project using Web Deploy.

image

The Web Deploy Server field should be set to

https://{sitename}.scm.azurewebsites.net/msdeploy.axd?site={sitename}.azurewebsites.net

Where {sitename} must be replaced by whatever you chose to name your Azure Website.  The Username and Password should be set to the credentials you provided in the Azure portal.

6)  Create your Runscope API tests.

image

7) Determine the trigger URL to initiate the tests.  An individual test can be triggered using the trigger URL on the test Settings page.

image

If you want to run all the tests defined in a bucket, there is also a trigger URL in the bucket settings page.

8) Configure AppVeyor to call Runscope Trigger URL.

image

Once this is all setup, as soon as you commit a change to the source code repo, AppVeyor will be notified of the commit and it will initiate a build.  Once the build is completed successfully, the Runscope trigger URL will be called and the newly deployed API will be tested.  Runscope notifications can be used to send emails, SMS messages or IMs if desired.

Image Credit: Lego Rube Goldberg machine https://flic.kr/p/8tA1H7


Darrel Miller: REST–The Chocolate Chip Cookie Analogy

At a recent conference, I found myself once again in a conversation about the meaning of the term REST.  I’ve had this conversation so many times, that I tend to forget that not everyone has heard my take on the subject.  The conversation ended with a “you should blog that…”. 

ChocolateChipCookies

Most developers are aware that REST is one of those terms that means different things to different people.  Lots of key presses have been wasted arguing about what is and isn’t RESTful.  I’m going to try and avoid that trap by making a particularly silly comparison to demonstrate why we should care about accurate use of terminology.

Constraints

KidCookieThe term REST has some similarities to the term “Chocolate Chip Cookie”.   A chocolate chip cookie is defined by two primary constraints.  It must be a cookie and it must contain chocolate chips.  There is no single official chocolate chip cookie recipe.   There are hundreds of different recipes, but the end result is always a cookie with chocolate chips in it.  More importantly, kids love them. 

The problem developers have with REST is that there is no single recipe for “how to do REST”.  Developers like very prescriptive guidance on how to achieve a goal.  The definition of REST simply provides a set of constraints and leaves out the details.

Desired Effect

When you are planning a birthday party and decide to buy some Chocolate Chip Cookies, you are not making that decision because you know Chocolate Chip Cookies contain flour and butter, but because you know kids love them, and you want the kids to be happy.

BirthdayParty

The REST constraints were chosen because they evoke certain characteristics in the systems that follow those constraints.  You choose to follow REST constraints because you want those desired effects.

Sometimes Oatmeal cookies are better

When taking kids on a long car ride, especially in warmer climates, chocolate chip cookies are not always the best choice for snacks.  Lots of kids like Oatmeal cookies too and they don’t make a mess of your back seat.  It is the effect that is important, not the ingredients.  You select the type of cookie that has the characteristics you desire.

MessyFace

Complying with the REST constraints requires a certain amount of work.  Maybe you don’t need all the characteristics that a REST system exhibits, or maybe you need additional ones.

False Expectations

However, if you tell your birthday party guests that they are going to get chocolate chip cookies, and you switch the chocolate chips for raisins, you are going to have some confused and upset kids.

UnhappyKid

This is the key point of the REST naming debacle.   Calling something REST that doesn’t conform to the constraints defined by REST is just a source of pain and confusion.  Some people argue that the popular use of the term REST is simply a subset of the constraints.  People have even tried to name these different sets of constraints: Hi-REST & Lo-REST, Fielding’s REST and Pop-REST.   None of these distinctions have really taken hold.

Rogue Constraints

Imagine how someone would be ridiculed if they came along and said,

our cookie making machine produces square cookies therefore we declare that chocolate chip cookies must be square. 

Or,

our chocolate chip cookie recipe contains pecans and they taste great, so we believe it is a best practice for all chocolate chip cookies to contain pecans.

Unfortunately, this has happened to the term REST.  For a variety of different reasons, new constraints have been invented and attributed to REST.  Sometimes, it is because someone believes the new constraint is a “best practice”, or often it is due to some framework limitation.

Landofconfusion

Land of confusion

The end result is many different definitions of REST.  There are thousands of recipes for making chocolate chip cookies, but the basic definition of what is a chocolate chip cookie remains the same: cookie + chocolate chip. 

The term REST should tell me that a system uses a layered architecture, uses caching, has a client-server architecture, interactions between the client and server are stateless and each layer applies the rules of the uniform interface constraint. 

Today, the term REST doesn’t guarantee that any of these constraints are being respected and makes the term fairly worthless in technical conversations.  The term HTTP API is much more accurate when describing most of today’s Web API.  Many of the core REST community have resorted to using the term Hypermedia API to describe an API that actually conforms to all of the REST constraints.

There is a point where all metaphors break down, and the difference between chocolate chip cookies and REST is that you can do a web search and easily find a recipe to make a great tasting chocolate chip cookie.  Unfortunately, you can’t do the same with REST due to the watering down of the term.

Let’s move on

DriveIntoSunsetIt is an unfortunate state of affairs, and one that is likely never to be resolved.  However, as long as you understand where we are and how we got here, we can move forward, get some real work done, stop debating what it means to be RESTful, and try not to make the same mistake with the next technical noun that comes along.

 

Image Credit : Cookies https://flic.kr/p/83Wef5
Image Credit: Kid with cookie
https://flic.kr/p/dMNwWR
Image Credit: Birthday Party https://flic.kr/p/6D1ag1
Image Credit: Messy Face https://flic.kr/p/PVrds
Image Credit: Unhappy kid https://flic.kr/p/i8SrkX
Image Credit: Land of confusion https://flic.kr/p/5eLaX7


Dominick Baier: IdentityServer & IdentityManager, Updates and the .NET Foundation

It’s busy times right now but we are still on track with our release plans for IdentityServer (and IdentityManager, which will get more love once IdentityServer is done). In fact we just pushed beta 3-4 to github and nuget, which mostly contains bug fixes and merged pull requests.

The other big news is that both projects joined the .NET Foundation as part of the announcements around open sourcing .NET. Joining the Foundation provides us with a strong organizational backbone to increase the visibility and attractiveness of IdentityServer and IdentityManager to both, new users and new committers. As a current user of one of these projects, this will provide even stronger long-term safety of your investments in the use of these frameworks.

If you want to contribute to any of the projects – you are more than welcome! Please have a look at our contribution guidelines and don’t hesitate to get in touch with us!

Also big thanks to our contributors – and especially Damian Hickey and Hadi Hariri who proved this week that this whole community thing is actually working!


Filed under: ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Chad England: Order the controllers in ASP.NET WebAPI Help

Recently I started a new API project for my company.  With this project I decided to give the Help files generator that Microsoft created a try.  Overall it looks like it will meet the needs of the project.  Today however I hit my first snag with it.  After I began to turn on routes for consumption I noticed in the help page that the routes was not sorted in any fashion.  To me, this can cause a level of annoyance for the folks needing to consume this. 

To solve this it was fairly trivial

  • Go to \Areas\HelpPage\Views\Help\
  • Open Index.cshtml
  • Locate the following line

ILookup<HttpControllerDescriptor, ApiDescription> apiGroups = Model

.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);

  • Replace that line with this one

ILookup<HttpControllerDescriptor, ApiDescription> apiGroups = Model

.OrderBy(d => d.ActionDescriptor.ControllerDescriptor.ControllerName)

.ToLookup(api => api.ActionDescriptor.ControllerDescriptor);

What we are doing here is first sorting the model before the lookup can be created.



Taiseer Joudeh: Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7

One of the main new features of ASP.NET 5 is unifying the programming model and combining MVC, Web API, and Web Pages in single framework called MVC 6. In previous versions of ASP.NET (MVC 4, and MVC 5) there were overlapping in the features between MVC and Web API frameworks, but the concrete implementation for both frameworks was totally different, with ASP.NET 5 the merging between those different frameworks will make it easier to develop modern web applications/HTTP services and increase code reusability.

The source code for this tutorial is available on GitHub.

Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7

In this post I’ve decided to give ASP.NET 5 – MVC 6 Web API a test drive, I’ll be building a very simple RESTful API from scratch by using MVC 6 Web API and the new Entity Framework 7, so we will learn the following:

  • Using the ASP.NET 5 empty template to build the Web API from scratch.
  • Overview of the new project structure in VS 2015 and how to use the new dependency management tool.
  • Configuring ASP.NET 5 pipeline to add only the components needed for our Web API.
  • Using EF 7 commands and the K Version Manager (KVM) to initialize and apply DB migrations.

To follow along with this post you need to install VS 2015 preview edition or you can provision a virtual machine using Azure Images as they have an Image with VS 2015 preview installed.

Step 1: Creating an empty web project

Open VS 2015 and select New Web Project (ASP.NET Web Application) as the image below, do not forget to set the .NET Framework to 4.5.1. You can name the project “Registration_MVC6WebApi”.

ASPNET5 New project

Now we’ll select the template named “ASP.NET 5 Empty” as the image below, this template is an empty template with no core dependencies on any framework.

MVC 6 Web API Project Template

Step 2: Adding the needed dependencies

Once the project is created you will notice that there is a file named “project.json” this file contains all your project settings along with a section for managing project dependencies on other frameworks/components.

We’ve used to manage packages/dependencies by using NuGet package manager, and you can do this with the new enhanced NuGet package manager tool which ships with VS 2015, but in our case we’ll add all the dependencies using the “project.json” file and benefit from the IntelliSense provided as the image below:

NuGet IntelliSense

So we will add the dependencies needed to configure our Web API, so open file “project.json” and replace the section “dependencies” with the section below:

"dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
        "EntityFramework": "7.0.0-beta1",
        "EntityFramework.SqlServer": "7.0.0-beta1",
        "EntityFramework.Commands": "7.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta1"
    }

The use for each dependency we’ve added as the below:

  • Microsoft.AspNet.Server.IIS: We want to host our Web API using IIS, so this package is needed. If you are planning to self-host your Web API then no need to add this package.
  • EntityFramework & EntityFramework.SqlServer: Our data provider for the Web API will be SQL Server. Entity Framework 7 can be configured to work with different data providers and not only relational databases, the data providers supported by EF 7 are: SqlServer, SQLite, AzureTableStorage, and InMemory. More about EF 7 data providers here.
  • EntityFramework.Commands: This package will be used to make the DB migrations command available in our Web API project by using KVM, more about this later in the post.
  • Microsoft.AspNet.Mvc: This is the core package which adds all the needed components to run Web API and MVC.
  • Microsoft.AspNet.Diagnostics: Basically this package will be used to display a nice welcome page when you request the base URI for the API in a browser. You can ignore this if you want, but it will be nice to display welcoming page instead of the 403 page displayed for older Web API 2.
  • Startup
  • Microsoft.Framework.ConfigurationModel.Json: This package is responsible to load and read the configuration file named “config.json”. We’ll add this file in a later step. This file is responsible to setup the “IConfiguration” object. I recommend to read this nice post about ASP.NET 5 new config files.

Last thing we need to add to the file “project.json” is a section named “commands” as the snippet below:

"commands": {
        "ef": "EntityFramework.Commands"
}

We’ve added short prefix “ef” for EntityFramework.Commands which will allow us to write EF commands such as initializing and applying DB migrations using KVM.

Step 3: Adding config.json configuration file

Now right click on your project and add new item of type “ASP.NET Configuration File” and name it “config.json”, you can think of this file as a replacement for the legacy Web.config file, for now this file will contain only our connection string to our SQL DB, I’m using SQL Express here and you can change this to your preferred SQL server.

{
    "Data": {
        "DefaultConnection": {
            "Connectionstring": "Data Source=.\\sqlexpress;Initial Catalog=RegistrationDB;Integrated Security=True;"
        }
    }
}

Note: This is a JSON file that’s why we are using escape characters in the connection string.

Step 4: Configuring the ASP.NET 5 pipeline for our Web API

This is the class which is responsible for adding the components needed in our pipeline, currently with the ASP.NET 5 empty template, the class is empty and our web project literally does nothing, I’ll add all the code in our Startup class at once then describe what each line of code is responsible for, so open file Startup.cs and paste the code below:

using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Registration_MVC6WebApi.Models;

namespace Registration_MVC6WebApi
{
    public class Startup
    {
        public static IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration().AddJsonFile("config.json").AddEnvironmentVariables();
        }
        public void ConfigureServices(IServiceCollection services)
        {
            // Add EF services to the services container.
            services.AddEntityFramework().AddSqlServer().AddDbContext<RegistrationDbContext>();

            services.AddMvc();

            //Resolve dependency injection
            services.AddScoped<IRegistrationRepo, RegistrationRepo>();
            services.AddScoped<RegistrationDbContext, RegistrationDbContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            app.UseMvc();

            app.UseWelcomePage();

        }
    }
}

What we’ve implemented in this class is the following:

  • The constructor for this class is responsible to read the settings in the configuration file “config.json” that we’ve defined earlier, currently we have only the connection string. So the static object “Configuration” contains this setting which we’ll use in the coming step.
  • The method “ConfigureServices” accepts parameter of type “IServiceCollection”, this method is called automatically when starting up the project, as well this is the core method responsible to register components in our pipeline, so the components we’ve registered are:
    • We’ve added “EntityFramework” using SQL Server as our data provider for the database context named “RegistrationDBContext”. We’ll add this DB context in next steps.
    • Added the MVC component to our pipeline so we can use MVC and Web API.
    • Lastly and one of the nice out of the box features which has been added to ASP.NET 5 is Dependency Injection without using any external IoC containers, notice how we are creating single instance scoped instance of our “IRegistrationRepo” by calling 
      services.AddScoped<IRegistrationRepo, RegistrationRepo>();
      . This instance will be available for the entire lifetime of our application life time of the request, we’ll implement the classes “IRegistrationRepo” and “RegistrationRepo” in next steps of this post. There is a nice post about ASP.NET 5 dependency injection can be read here. (Update by Nick Nelson to use Scoped injection instead of using Singleton instance because DbContext is not thread safe).
  • Lastly the method “Configure” accepts parameter of type “IApplicationBuilder”, this method configures the pipeline to use MVC and show the welcome page. Do not ask me why we have to call “AddMvc” and “UseMvc” and what is the difference between both :) I would like to hear an answer if someone knows the difference or maybe this will be changed in the coming release of ASP.NET 5. (Update: Explanation of this pattern in the comments section).

Step 5: Adding Models, Database Context, and Repository

Now we’ll add a file named “Course” which contains two classes: “Course” and “CourseStatusModel”, those classes will represents our domain data model, so for better code organizing add new folder named “Models” then add the new file containing the the code below:

using System;
using System.ComponentModel.DataAnnotations;

namespace Registration_MVC6WebApi.Models
{
    public class Course
    {
        public int Id { get; set; }
        [Required]
        [StringLength(100, MinimumLength = 5)]
        public string Name { get; set; }
        public int Credits { get; set; }
    }

    public class CourseStatusModel
    {
        public int Id { get; set; }
        public string Description { get; set; }
    }
}

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “RegistrationDbContext” then paste the code snippet below:

using Microsoft.Data.Entity;
using System;
using Microsoft.Data.Entity.Metadata;

namespace Registration_MVC6WebApi.Models
{
    public class RegistrationDbContext :DbContext
    {
        public DbSet<Course> Courses { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
        }
    }
}

Basically what we’ve implemented here is adding our Courses data model as DbSet so it will represent a database table once we run the migrations, note that there is a new method named “OnConfiguration” where we can override it so we’ll be able to specify the data provider which needs to work with our DB context.

In our case we’ll use SQL Server, the constructor for “UseSqlServer” extension method accepts a parameter of type connection string, so we’ll read it from our “config.json” file by specifying the key “Data:DefaultConnection:ConnectionString” for the “Configuration” object we’ve created earlier in Startup class.

Note: This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.

Lastly we need to add the interface “IRegistrationRepo” and the implementation for this interface “RegistrationRepo”, so add two new files under “Models” folder named “IRegistrationRepo” and “RegistrationRepo” and paste the two code snippets below:

using System;
using System.Collections;
using System.Collections.Generic;

namespace Registration_MVC6WebApi.Models
{
    public interface IRegistrationRepo
    {
        IEnumerable<Course> GetCourses();
        Course GetCourse(int courseId);
        Course AddCourse(Course course);
        bool DeleteCourse(int courseId);
    }
}

using System;
using System.Collections.Generic;
using System.Linq;


namespace Registration_MVC6WebApi.Models
{
    public class RegistrationRepo : IRegistrationRepo
    {
        private readonly RegistrationDbContext _db;

        public RegistrationRepo(RegistrationDbContext db)
        {
            _db = db;
        }
        public Course AddCourse(Course course)
        {
            _db.Courses.Add(course);

            if (_db.SaveChanges() > 0)
            {
                return course;
            }
            return null;

        }

        public bool DeleteCourse(int courseId)
        {
            var course = _db.Courses.FirstOrDefault(c => c.Id == courseId);
            if (course != null)
            {
                _db.Courses.Remove(course);
                return _db.SaveChanges() > 0;
            }
            return false;
        }

        public Course GetCourse(int courseId)
        {
            return _db.Courses.FirstOrDefault(c => c.Id == courseId);
        }

        public IEnumerable<Course> GetCourses()
        {
            return _db.Courses.AsEnumerable();
        }
    }
}

The implementation here is fairly simple, what worth noting here is how we’ve passed “RegistrationDbContext” as parameter for our “RegistrationRepo” constructor so we’ve implemented Constructor Injection, this will not work if we didn’t configure this earlier in our “Startup” class.

Step 6: Installing KVM (K Version Manager)

After we’ve added our Database context and our domain data models, we can use migrations to create the database, with previous version of ASP.NET we’ve used NuGet package manager for these type of tasks, but with ASP.NET 5 we can use command prompt using various K* commands.

What is KVM (K Version Manager)?  KVM is a Powershell script used to get the runtime and manage multiple versions of it being on the machine at the same time, you can read more about it here.

Now to install KVM for the first time you have to do the following steps:

1. Open a command prompt with Run as administrator.
2. Run the following command:

@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"

3. The script installs KVM for the current user.
4. Exit the command prompt window and start another as an administrator (you need to start a new command prompt to get the updated path environment).
5. Upgrade KVM with the following command:

KVM upgrade

We are ready now to run EF migrations as the step below:

Step 7: Initializing and applying migrations for our database

Now our command prompt is ready to understand K commands and Entity Framework commands, first step to do is to change the directory to the project directory. The project directory contains the “project.json” file as the image below:

EF7 Migrations
So in the command prompt we need to run the 2 following commands:

k ef migration add initial
k ef migration apply

Basically the first command will add migration file with the name format (<date>_<migration name>) so we’ll end up having file named “201411172303154_initial.cs” under folder named “Migrations” in our project. This auto generated file contains the code needed to to add our Courses table to our database, the newly generated files will show up under your project as the image below:

EF7 Migrations 2
The second command will apply those migrations and create the database for us based on the connection string we’ve specified earlier in file “config.json”.

Note: the “ef” command comes from the settings that we’ve specified earlier in file “project.json” under section “commands”.

Step 8: Adding GET methods for Courses Controller

The controller is a class which is responsible to handle HTTP requests, with ASP.NET 5 our Web API controller will inherit from “Controller” class not anymore from “ApiController”, so add new folder named “Controllers” then add new controller named “CoursesController” and paste the code below:

using Microsoft.AspNet.Mvc;
using Registration_MVC6WebApi.Models;
using System;
using System.Collections.Generic;

namespace Registration_MVC6WebApi.Controllers
{
    [Route("api/[controller]")]
    public class CoursesController : Controller
    {
        private IRegistrationRepo _registrationRepo;

        public CoursesController(IRegistrationRepo registrationRepo)
        {
            _registrationRepo = registrationRepo;
        }

        [HttpGet]
        public IEnumerable<Course> GetAllCourses()
        {
            return _registrationRepo.GetCourses();
        }

        [HttpGet("{courseId:int}", Name = "GetCourseById")]
        public IActionResult GetCourseById(int courseId)
        {
            var course = _registrationRepo.GetCourse(courseId);
            if (course == null)
            {
                return HttpNotFound();
            }

            return new ObjectResult(course);
        }

    }
}

What we’ve implemented in the controller class is the following:

  • The controller is attribute with Route attribute as the following
    [Route("api/[controller]")]
    so any HTTP requests that match the template are routed to the controller. The “[controller]” part in the template URL means to substitute the controller class name, minus the “Controller” suffix. In our case and for “CoursesController” class, the route template is “api/courses”.
  • We’ve defined two HTTP GET methods, the first one “GetAllCourses” is attributed with “[HttpGet]” and it returns a .NET object which is serialized in the body of the response using the default JSON format.
  • The second HTTP GET method “GetCourseById” is attributed with “[HttpGet]“. For this method we’ve specified a constraint on the parameter “courseId”, the parameter should be of integer data type. As well we’ve specified a name for this method “GetCourseById” which we’ll use in the next step. Last thing this method returns object of type IActionResult which gives us flexibility to return different actions results based on our logic, in our case we will return HttpNotFound if the course does not exist or we can return serialized JSON object of the course when the course is found.
  • Lastly notice how we are passing the “IRegistrationRepo” as a constructor for our CoursesController, by doing this we are implementing Constructor Injection.

Step 9: Adding POST and DELETE methods for Courses Controller

Now we want to implement another two HTTP methods which allow us to add new Course or delete existing one, so open file “CoursesController” and paste the code below:

[HttpPost]
public IActionResult AddCourse([FromBody] Course course)
{
	if (!ModelState.IsValid)
	{
		Context.Response.StatusCode = 400;
		return new ObjectResult(new CourseStatusModel { Id = 1 , Description= "Course model is invalid" });
	}
	else
	{
	   var addedCourse =  _registrationRepo.AddCourse(course);

		if (addedCourse != null)
		{
			string url = Url.RouteUrl("GetCourseById", new { courseId = course.Id }, Request.Scheme, Request.Host.ToUriComponent());

			Context.Response.StatusCode = 201;
			Context.Response.Headers["Location"] = url;
			return new ObjectResult(addedCourse);
		}
		else
		{
			Context.Response.StatusCode = 400;
			return new ObjectResult(new CourseStatusModel { Id = 2, Description = "Failed to save course" });
		}
	   
	}
}

What we’ve implemented here is the following:

  • For method “AddCourse”:
    • Add new HTTP POST method which is responsible to create new Course, this method accepts Course object which is coming from the request body then Web API framework will deserialize this to CLR Course object.
    • If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code and an object containing description of the validation error. Thanks for Yishai Galatzer for spotting this out because I was originally returning response of type “text/plain” always regarding the “Accept” header value set by the client. The point below contains the fix.
    • If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code, and in the response body we’ll return an instance of a POCO class(CourseStatusModel) containing fictional Id and description of the validation error.
    • If the course created successfully then we’ll build a location URI which points to our new created course i.e. (/api/courses/4) and set this URI in the “Location” header for the response.
    • Lastly we are returning the created course object in the response body.
  • For method “DeleteCourse”:
    • Add new HTTP DELETE method which is responsible for deleting existing course, this method accepts integer courseId.
    • If the course has been deleted successfully we’ll return HTTP status 204 (No content)
    • If the passed courseId doesn’t exists we will return HTTP status 404.

Note: I believe that the IhttpActionResult response which got introduced in Web API 2 is way better than IActionResult, please drop me a comment if someone knows how to use IhttpActionResult with MVC6.

The source code for this tutorial is available on GitHub.

That’s all for now folks! I’m still learning the new features in ASP.NET 5, please drop me a comment if you have better way implementing this tutorial or you spotted something that could be done in a better way.

Follow me on Twitter @tjoudeh

References

The post Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7 appeared first on Bit of Technology.


Darrel Miller: Microsoft: Open source and cross-platform all the things

It was announced today that Microsoft will be delivering a cross-platform and open source, cloud-optimized version of the .Net framework.

AllTheThings

Today’s announcement is a culmination of a series of changes that have been happening over the past few years in certain parts of Microsoft.  Through the persistence of numerous Microsoft employees and the encouragement by the .net developer community, OSS is finally becoming accepted as an integral part of Microsoft’s business model

Wait, there’s more…

Surprisingly, releasing the source code to this new .net Framework is probably the least significant part of the announcement.  For as long as I remember, Microsoft have had a culture of creating strong coupling between Microsoft’s own products.   This is epitomized in the developer world by the fact that it is very difficult to get build machines to function without have Visual Studio on them.  This is just one example, but this has been a pervasive attitude throughout the company.

Time to leave the nest

In my opinion, today’s announcement is a declaration that Microsoft have grown up.  They have accepted the fact that their products must succeed on their own merit, and not because a customer chose one product and became locked into an entire eco-system.

.net on every server

The new cloud-optimized .net runtime will run on Mac’s and on Linux.  You can use your favorite code editor to write and compile .net applications.  There is no more coupling with Visual Studio.  In fact, in the last few days, I have experienced first hand that MS employees are working hard to get features like, intellisense, syntax/error highlighting features into editors like Sublime, Atom, Emacs and vim. With the announcement of Visual Studio Community edition, which is almost on feature parity with the Pro edition, the old Microsoft would just have said, “hey, we’re giving you a free edition, why would you want to use anything else”.

Haven’t we heard this all before?

Microsoft have made “open” announcements before and have had less than stellar results.  I think one of the reasons has been that it has taken a very long time to chip away at the internal cultural armor within Microsoft.  At the MVP Summit we had the opportunity to watch a panel discussion with some senior Microsoft people who were clearly 100% behind this open approach.

Best of breed should always win

One indication that this shift in culture is more than skin deep is the fact that Microsoft teams, more and more, are choosing to use external tools instead of being required to use their own.  The new Cloud-Optimized CLR and ASP.NET vNext are all being developed in Github repositories.  To file an issue, you can create a Github issue and if you think you can fix a bug, then send a pull request.  Github is the king of “social-coding” which suits an OSS model well.  Microsoft’s own TFS source code control has always been aimed at the enterprise space which often has different needs.  Microsoft’s teams get to use the best product for their own particular requirements and Microsoft products need to compete purely on merit.

Oh, no, not another .net framework!

I must admit, when I first heard about the cloud-optimized runtime, I was underwhelmed.  Why do we need yet another variant of the .net framework?  Why is it server-optimized?  What about mobile and desktop?  Well, technically, the CLR for this stack is not new.  It’s the Silverlight CoreCLR.  I’ll wait for you to stop snickering…. It is also the CLR used to power .net applications on Windows Phone 8 and Windows 8 apps. The CoreCLR is a proven, lightweight version of the CLR that happens to be ideal for creating lightweight web applications. When this lightweight CLR is combined with the new K Runtime Environment, the result is compelling.  Different versions of the CLR can sit side by side and switching between them is trivial.  The .Net framework libraries have been sliced up into more then 70 nuget packages so that only the functionality that is needed is pulled in. 

A victim of success

One of the major challenges with the .net framework in the past is that it had become very large to deploy, very slow for the team to get new features into the framework and every new major version, the team has attempted a new, hopefully less painful way, to deliver those changes.  The result has been inconsistent and confusing.  The KRE does enough things differently that we may finally have something that can allow the ,net framework to evolve quickly and painlessly.

K for Kool

The KRE finally breaks the dependency on the Global Assembly Cache that has been a critical part of .Net since it’s inception.  However, as the .net framework team like to say, they are “in the app compat business”.  There will still be full CLR framework support, that still uses the GAC for applications that run under the K runtime.  The new CoreCLR also changes the rules with regards to strong naming.  Microsoft are now saying quite openly that they do not recommend strong naming for Open Source projects, which will come as a great relief for many developers.

This is just the beginning

It was not until I realized the impact that open-sourcing big chunks of the .Net CLR would have on the Mono framework, that I started to appreciate the bigger picture.  The plan for the future, as I understand it, is that Mono will start to replace some of the less optimized parts of Mono with MS source code.  Future versions of Mono will take advantage of more pieces of the CLR infrastructure.  I can envision a future where some combination of Mono / CoreCLR would become a “client optimized” CLR stack.  This would bring a fully supported and optimized .net to every platform that matters.

How is this going to help us developers?

Now that pieces of the .net frameworks and Core CLR are easily accessible on Github, it should really help developers get a better understand of how the .Net framework behaves and by being able to see the commit history and related issues we should start to get a picture of why it behaves that way.

The .Net and Core CLR source code is MIT licensed which now allows us to copy and modify the code.  This is huge.  There is all sorts of useful code in the framework that is marked as internal because MS didn’t want to support in the public interface.  We can now re-use this code.  Microsoft have also attached their Patent Promise to the repositories.

Cross platform is becoming a critical part of the Microsoft developer’s workload.  With easy access to Linux VMs on the server side on Azure and tools like Xamarin that allow C# across iOS and Android, Microsoft developers can reach every platform.  Having Microsoft recognize cross platform as a 1st class concern, rather than just a feature checkbox, is going to make building products with wide reach much easier.

This is a rebirth of Microsoft and I look forward to being part of it.


Dominick Baier: MVP Summit Hackathon: IdentityServer v3 on ASP.NET vNext

Today we had a chance to sit together with the ASP.NET team and try moving IdentityServer to vNext.

There are two fundamental approaches for doing that – migrate the code and middleware to the new APIs or host IdentityServer as-is as an OWIN component.

We went for the latter – and lo and behold – after two hours we got everything up and running. Big thanks to Chris, Lou and Dan from the ASP.NET team!

This allows us (at least for the time being) to run IdentityServer on both ASP.NET vCurrent as well as vNext. This will not give us support for the new CoreCLR – but we also have a plan how to tackle that.

If you want to try it out yourself – the code can be found here.

2014-11-06 12.04.53

Update: two hours later, Christian got everything also running on Ubuntu!

leastprivilege_2014-Nov.-06


Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: IdentityServer v3 Beta 3

Some of our users already found out and broke the news – so here’s my official post ;)

Beta 3 has been released to github and nuget – 107 commits since Beta 2-1…new features include:

  • Anti-forgery token support
  • Permission self-service page for users
  • Added support to add all claims of a user to a token (and support for implementation specific claims rules)
  • Added more documentation and comments
  • Added token handle and authorization code hashing
  • New view system and support for file system based assets
  • Support for WS-Federation, OpenID Connect and social external IdPs
  • Support for upstream federated sign-out
  • Added flag to hide scopes from discovery document
  • Re-worked claims filtering and normalization
  • Added support for more authentication scenarios, e.g. client certificates

Documentation will be updated, and new samples will be added ASAP – bear with us.

Again a massive thanks to all contributors and the people giving feedback and filing issues – you make IdentityServer better every day!


Filed under: ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Taiseer Joudeh: JSON Web Token in ASP.NET Web API 2 using Owin

In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separate the Authorization Server and the Resource Server by unifying the “decryptionKey” and “validationKey” key values in machineKey node in the web.config file for the Authorization and the Resource server. So once the user request an access token from the Authorization server, the Authorization server will use this unified key to encrypt the access token, and at the other end when the token is sent to the Resource server, it will use the same key to decrypt this access token and extract the authentication ticket from it.

The source code for this tutorial is available on GitHub.

This way works well if you have control on your Resource servers (Audience) which will rely on your Authorization server (Token Issuer) to obtain access tokens from, in other words you are fully trusting those Resource servers so you are sharing with them the same “decryptionKey” and “validationKey” values.

But in some situations you might have big number of Resource servers rely on your Authorization server, so sharing the same “decryptionKey” and “validationKey” keys with all those parties become inefficient process as well insecure, you are using the same keys for multiple Resource servers, so if a key is compromised all the other Resource servers will be affected.

To overcome this issue we need to configure the Authorization server to issue access tokens using JSON Web Tokens format (JWT) instead of the default access token format, as well on the Resource server side we need to configure it to consume this new JWT access tokens, as well you will see through out this post that there is no need to unify the “decryptionKey” and “validationKey” key values anymore if we used JWT.

Featured Image

What is JSON Web Token (JWT)?

JSON Web Token is a security token which acts as a container for claims about the user, it can be transmitted easily between the Authorization server (Token Issuer), and the Resource server (Audience), the claims in JWT are encoded using JSON which make it easier to use especially in applications built using JavaScript.

JSON Web Tokens can be signed following the JSON Web Signature (JWS) specifications, as well it can be encrypted following the JSON Web Encryption (JWE) specifications, in our case we will not transmit any sensitive data in the JWT payload, so we’ll only sign this JWT to protect it from tampering during the transmission between parties.

JSON Web Token (JWT) Format

Basically the JWT is a string which consists of three parts separated by a dot (.) The JWT parts are: <header>.<payload>.<signature>.

The header part is JSON object which contains 2 nodes always and looks as the following: 

{ "typ": "JWT", "alg": "HS256" }
 The “type” node has always “JWT” value, and the node “alg” contains the algorithm used to sign the token, in our case we’ll use “HMAC-SHA256″ for signing.

The payload part is JSON object as well which contains all the claims inside this token, check the example shown in the snippet below:

{
  "unique_name": "SysAdmin",
  "sub": "SysAdmin",
  "role": [
    "Manager",
    "Supervisor"
  ],
  "iss": "http://myAuthZServer",
  "aud": "379ee8430c2d421380a713458c23ef74",
  "exp": 1414283602,
  "nbf": 1414281802
}

All those claims are not mandatory  in order to build JWT, you can read more about JWT claims here. In our case we’ll always use those set of claims in the JWT we are going to issue, those claims represent the below:

  • The “sub” (subject) and “unique_claim” claims represent the user name this token issued for.
  • The “role” claim represents the roles for the user.
  • The “iss” (issuer) claim represents the Authorization server (Token Issuer) party.
  • The “aud” (audience) claim represents the recipients that the JWT is intended for (Relying Party – Resource Server). More on this unique string later in this post.
  • The “exp” (expiration time) claim represents the expiration time of the JWT, this claim contains UNIX time value.
  • The “nbf” (not before) claim represent the time which this JWT must not be used before, this claim contains UNIX time vale.

Lastly the signature part of the JWT is created by taking the header and payload parts, base 64 URL encode them, then concatenate them with “.”, then use the “alg” defined in the <header> part to generate the signature, in our case “HMAC-SHA256″. The resulting part of this signing process is byte array which should be base 64 URL encoded then concatenated with the <header>.<payload> to produce a complete JWT.

JSON Web Tokens support in ASP.NET Web API and Owin middleware.

There is no direct support for issuing JWT in ASP.NET Web API or ready made Owin middleware responsible for doing this, so in order to start issuing JWTs we need to implement this manually by implementing the interface “ISecureDataFormat” and implement the method “Protect”. More in this later. But for consuming the JWT in a Resource server there is ready middleware named “Microsoft.Owin.Security.Jwt” which understands validates, and and de-serialize JWT tokens with minimal number of line of codes.

So most of the heavy lifting we’ll do now will be in implementing the Authorization Server.

What we’ll build in this tutorial?

We’ll build a single Authorization server which issues JWT using ASP.NET Web API 2 on top of Owin middleware, the Authorization server is hosted on Azure (http://JwtAuthZSrv.azurewebsites.net) so you can test it out by adding new Resource servers. Then we’ll build a single Resource server (audience) which will process JWTs issued by our Authorization server only.

I’ll split this post into two sections, the first section will be for creating the Authorization server, and the second section will cover creating Resource server.

The source code for this tutorial is available on GitHub.

Section 1: Building the Authorization Server (Token Issuer)

Step 1.1: Create the Authorization Server Web API Project

Create an empty solution and name it “JsonWebTokensWebApi” then add a new ASP.NET Web application named “AuthorizationServer.Api”, the selected template for the project will be “Empty” template with no core dependencies. Notice that the authentication is set to “No Authentication”.

Step 1.2: Install the needed NuGet Packages:

Open package manger console and install the below Nuget packages:

Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Cors -Version 3.0.0
Install-Package Microsoft.Owin.Security.OAuth -Version 3.0.0
Install-Package System.IdentityModel.Tokens.Jwt -Version 4.0.0
Install-Package Thinktecture.IdentityModel.Core Version 1.2.0

You can refer to the previous post if you want to know what each package is responsible for. The package named “System.IdentityModel.Tokens.Jwt” is responsible for validating, parsing and generating JWT tokens. As well we’ve used the package “Thinktecture.IdentityModel.Core” which contains class named “HmacSigningCredentials”  which will be used to facilitate creating signing keys.

Step 1.3: Add Owin “Startup” Class:

Right click on your project then add a new class named “Startup”. It will contain the code below:

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            // Web API routes
            config.MapHttpAttributeRoutes();
            
            ConfigureOAuth(app);
            
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            
            app.UseWebApi(config);

        }

        public void ConfigureOAuth(IAppBuilder app)
        {

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/oauth2/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new CustomOAuthProvider(),
                AccessTokenFormat = new CustomJwtFormat("http://jwtauthzsrv.azurewebsites.net")
            };

            // OAuth 2.0 Bearer Access Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

        }
    }

Here we’ve created new instance from class “OAuthAuthorizationServerOptions” and set its option as the below:

  • The path for generating JWT will be as :”http://jwtauthzsrv.azurewebsites.net/oauth2/token”.
  • We’ve specified the expiry for token to be 30 minutes
  • We’ve specified the implementation on how to validate the client and Resource owner user credentials in a custom class named “CustomOAuthProvider”.
  • We’ve specified the implementation on how to generate the access token using JWT formats, this custom class named “CustomJwtFormat” will be responsible for generating JWT instead of default access token using DPAPI, note that both are using bearer scheme.

We’ll come to the implementation of both class later in the next steps.

Step 1.4: Resource Server (Audience) Registration:

Now we need to configure our Authorization server to allow registering Resource server(s) (Audience), this step is very important because we need a way to identify which Resource server (Audience) is requesting the JWT token, so the Authorization server will be able to issue JWT token for this audience only.

The minimal needed information to register a Recourse server into an Authorization server are a unique Client Id, and shared symmetric key. For the sake of keeping this tutorial simple I’m persisting those information into a volatile dictionary so the values for those Audiences will be removed from the memory if IIS reset toke place, for production scenario you need to store those values permanently on a database.

Now add new folder named “Entities” then add new class named “Audience” inside this class paste the code below:

public class Audience
    {
        [Key]
        [MaxLength(32)]
        public string ClientId { get; set; }
        
        [MaxLength(80)]
        [Required]
        public string Base64Secret { get; set; }
        
        [MaxLength(100)]
        [Required]
        public string Name { get; set; }
    }

Then add new folder named “Models” the add new class named “AudienceModel” inside this class paste the code below:

public class AudienceModel
    {
        [MaxLength(100)]
        [Required]
        public string Name { get; set; }
    }

Now add new class named “AudiencesStore” and paste the code below:

public static class AudiencesStore
    {
        public static ConcurrentDictionary<string, Audience> AudiencesList = new ConcurrentDictionary<string, Audience>();
        
        static AudiencesStore()
        {
            AudiencesList.TryAdd("099153c2625149bc8ecb3e85e03f0022",
                                new Audience { ClientId = "099153c2625149bc8ecb3e85e03f0022", 
                                                Base64Secret = "IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw", 
                                                Name = "ResourceServer.Api 1" });
        }

        public static Audience AddAudience(string name)
        {
            var clientId = Guid.NewGuid().ToString("N");

            var key = new byte[32];
            RNGCryptoServiceProvider.Create().GetBytes(key);
            var base64Secret = TextEncodings.Base64Url.Encode(key);

            Audience newAudience = new Audience { ClientId = clientId, Base64Secret = base64Secret, Name = name };
            AudiencesList.TryAdd(clientId, newAudience);
            return newAudience;
        }

        public static Audience FindAudience(string clientId)
        {
            Audience audience = null;
            if (AudiencesList.TryGetValue(clientId, out audience))
            {
                return audience;
            }
            return null;
        }
    }

Basically this class acts like a repository for the Resource servers (Audiences), basically it is responsible for two things, adding new audience and finding exiting one.

Now if you take look on method “AddAudience” you will notice that we’ve implemented the following:

  • Generating random string of 32 characters as an identifier for the audience (client id).
  • Generating 256 bit random key using the “RNGCryptoServiceProvider” class then base 64 URL encode it, this key will be shared between the Authorization server and the Resource server only.
  • Add the newly generated audience to the in-memory “AudiencesList”.
  • The “FindAudience” method is responsible for finding an audience based on the client id.
  • The constructor of the class contains fixed audience for the demo purpose.

Lastly we need to add an end point in our Authorization server which allow registering new Resource servers (Audiences), so add new folder named “Controllers” then add new class named “AudienceController” and paste the code below:

[RoutePrefix("api/audience")]
    public class AudienceController : ApiController
    {
        [Route("")]
        public IHttpActionResult Post(AudienceModel audienceModel)
        {
            if (!ModelState.IsValid) {
                return BadRequest(ModelState);
            }

            Audience newAudience = AudiencesStore.AddAudience(audienceModel.Name);

            return Ok<Audience>(newAudience);

        }
    }

This end point can be accessed by issuing HTTP POST request to the URI http://jwtauthzsrv.azurewebsites.net/api/audience as the image below, notice that the Authorization server is responsible for generating the client id and the shared symmetric key. This symmetric key should not be shared with any party except the Resource server (Audience) requested it.

Note: In real world scenario the Resource server (Audience) registration process won’t be this trivial, you might go through workflow approval. Sharing the key will take place using a secure admin portal, as well you might need to provide the audience with the ability to regenerate the key in case it get compromised.

Register Audience

Step 1.5: Implement the “CustomOAuthProvider” Class

Now we need to implement the code responsible for issuing JSON Web Token when the requester issue HTTP POST request to the URI: http://jwtauthzsrv.azurewebsites.net/oauth2/token the request will look as the image below, notice how we are setting the client id for for the Registered resource (audience) from the previous step using key (client_id).

Issue JWT

To implement this we need to add new folder named “Providers” then add new class named “CustomOAuthProvider”, paste the code snippet below:

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
    {

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            string symmetricKeyAsBase64 = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return Task.FromResult<object>(null);
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return Task.FromResult<object>(null);
            }
            
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            //Dummy check here, you need to do your DB checks against memebrship system http://bit.ly/SPAAuthCode
            if (context.UserName != context.Password)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect");
                //return;
                return Task.FromResult<object>(null);
            }

            var identity = new ClaimsIdentity("JWT");

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Manager"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {
                         "audience", (context.ClientId == null) ? string.Empty : context.ClientId
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            return Task.FromResult<object>(null);
        }
    }

As you notice this class inherits from class “OAuthAuthorizationServerProvider”, we’ve overridden two methods “ValidateClientAuthentication” and “GrantResourceOwnerCredentials”

  • The first method “ValidateClientAuthentication” will be responsible for validating if the Resource server (audience) is already registered in our Authorization server by reading the client_id value from the request, notice that the request will contain only the client_id without the shared symmetric key. If we take the happy scenario and the audience is registered we’ll mark the context as a valid context which means that audience check has passed and the code flow can proceed to the next step which is validating that resource owner credentials (user who is requesting the token).
  • The second method “GrantResourceOwnerCredentials” will be responsible for validating the resource owner (user) credentials, for the sake of keeping this tutorial simple I’m considering that each identical username and password combination are valid, in read world scenario you will do your database checks against membership system such as ASP.NET Identity, you can check this in the previous post.
  • Notice that we are setting the authentication type for those claims to “JWT”, as well we are passing the the audience client id as a property of the “AuthenticationProperties”, we’ll use the audience client id in the next step.
  • Now the JWT access token will be generated when we call “context.Validated(ticket), but we still need to implement the class “CustomJwtFormat” we talked about in step 1.3.

Step 1.5: Implement the “CustomJwtFormat” Class

This class will be responsible for generating the JWT access token, so what we need to do is to add new folder named “Formats” then add new class named “CustomJwtFormat” and paste the code below:

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
    {
        private const string AudiencePropertyKey = "audience";

        private readonly string _issuer = string.Empty;

        public CustomJwtFormat(string issuer)
        {
            _issuer = issuer;
        }

        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = data.Properties.Dictionary.ContainsKey(AudiencePropertyKey) ? data.Properties.Dictionary[AudiencePropertyKey] : null;

            if (string.IsNullOrWhiteSpace(audienceId)) throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");

            Audience audience = AudiencesStore.FindAudience(audienceId);

            string symmetricKeyAsBase64 = audience.Base64Secret;
  
            var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);

            var signingKey = new HmacSigningCredentials(keyByteArray);

            var issued = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;

            var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return jwt;
        }

        public AuthenticationTicket Unprotect(string protectedText)
        {
            throw new NotImplementedException();
        }
    }

What we’ve implemented in this class is the following:

  • The class “CustomJwtFormat” implements the interface “ISecureDataFormat<AuthenticationTicket>”, the JWT generation will take place inside method “Protect”.
  • The constructor of this class accepts the “Issuer” of this JWT which will be our Authorization server, this can be string or URI, in our case we’ll fix it to URI with the value “http://jwtauthzsrv.azurewebsites.net”
  • Inside “Protect” method we are doing the following:
    1. Reading the audience (client id) from the Authentication Ticket properties, then getting this audience from the In-memory store.
    2. Reading the Symmetric key for this audience and Base64 decode it to byte array which will be used to create a HMAC265 signing key.
    3. Preparing the raw data for the JSON Web Token which will be issued to the requester by providing the issuer, audience, user claims, issue date, expiry date, and the signing Key which will sign the JWT payload.
    4. Lastly we serialize the JSON Web Token to a string and return it to the requester.
  • By doing this requester for an access token from our Authorization server will receive a signed token which contains claims for a certain resource owner (user) and this token intended to certain Resource server (audience) as well.

So if we need to request a JWT from our Authorization server for a user named “SuperUser” that needs to access the Resource server (audience) “099153c2625149bc8ecb3e85e03f0022″, all we need to do is to issue HTTP POST to the token end point (http://jwtauthzsrv.azurewebsites.net/oauth2/token) as the image below:

Issue JWT2

The result for this will be the below JSON Web Token:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6IlN1cGVyVXNlciIsInN1YiI6IlN1cGVyVXNlciIsInJvbGUiOlsiTWFuYWdlciIsIlN1cGVydmlzb3IiXSwiaXNzIjoiaHR0cDovL2p3dGF1dGh6c3J2LmF6dXJld2Vic2l0ZXMubmV0IiwiYXVkIjoiMDk5MTUzYzI2MjUxNDliYzhlY2IzZTg1ZTAzZjAwMjIiLCJleHAiOjE0MTQzODEyODgsIm5iZiI6MTQxNDM3OTQ4OH0.pZffs_TSXjgxRGAPQ6iJql7NKfRjLs1WWSliX5njSYU

There is an online JWT debugger tool named jwt.io that allows you to paste the encoded JWT and decode it so you can interpret the claims inside it, so open the tool and paste the JWT above and you should receive response as the image below, notice that all the claims are set properly including the iss, aud, sub,role, etc…

One thing to notice here that there is red label which states that the signature is invalid, this is true because this tool doesn’t know about the shared symmetric key issued for the audience (099153c2625149bc8ecb3e85e03f0022).

So if we decided to share this symmetric key with the tool and paste the key in the secret text box; we should receive green label stating that signature is valid, and this is identical to the implementation we’ll see in the Resource server when it receives a request containing a JWT.

jwtio

Now the Authorization server (Token issuer) is able to register audiences and issue JWT tokens, so let’s move to adding a Resource server which will consume the JWT tokens.

Section 2: Building the Resource Server (Audience)

Step 2.1: Creating the Resource Server Web API Project

Add a new ASP.NET Web application named “ResourceServer.Api”, the selected template for the project will be “Empty” template with no core dependencies. Notice that the authentication is set to “No Authentication”.

Step 2.2: Installing the needed NuGet Packages:

Open package manger console and install the below Nuget packages:

Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Cors -Version 3.0.0
Install-Package Microsoft.Owin.Security.Jwt -Version 3.0.0

The package “Microsoft.Owin.Security.Jwt” is responsible for protecting the Resource server resources using JWT, it only validate and de-serialize JWT tokens.

Step 2.3: Add Owin “Startup” Class:

Right click on your project then add a new class named “Startup”. It will contain the code below:

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            ConfigureOAuth(app);

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
           
            app.UseWebApi(config);

        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            var issuer = "http://jwtauthzsrv.azurewebsites.net";
            var audience = "099153c2625149bc8ecb3e85e03f0022";
            var secret = TextEncodings.Base64Url.Decode("IxrAjDoa2FqElO7IhrSrUJELhUckePEPVpaePlS_Xaw");

            // Api controllers with an [Authorize] attribute will be validated with JWT
            app.UseJwtBearerAuthentication(
                new JwtBearerAuthenticationOptions
                {
                    AuthenticationMode = AuthenticationMode.Active,
                    AllowedAudiences = new[] { audience },
                    IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                    {
                        new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
                    }
                });

        }
    }

This is the most important step in configuring the Resource server to trust tokens issued by our Authorization server (http://jwtauthzsrv.azurewebsites.net), notice how we are providing the values for the issuer, audience (client id), and the shared symmetric secret we obtained once we registered the resource with the authorization server.

By providing those values to JwtBearerAuthentication middleware, this Resource server will be able to consume only JWT tokens issued by the trusted Authorization server and issued for this audience only.

Note: Always store keys in config files not directly in source code.

Step 2.4: Add new protected controller

Now we want to add a controller which will serve as our protected resource, this controller will return list of claims for the authorized user, those claims for sure are encoded within the JWT we’ve obtained from the Authorization Server. So add new controller named “ProtectedController” under “Controllers” folder and paste the code below:

[Authorize]
    [RoutePrefix("api/protected")]
    public class ProtectedController : ApiController
    {
        [Route("")]
        public IEnumerable<object> Get()
        {
            var identity = User.Identity as ClaimsIdentity;

            return identity.Claims.Select(c => new
            {
                Type = c.Type,
                Value = c.Value
            });
        }
    }

Notice how we attribute the controller with [Authorize] attribute which will protect this resource and only will authentic HTTP GET requests containing a valid JWT access token, with valid I mean:

  • Not expired JWT.
  • JWT issued by our Authorization server (http://jwtauthzsrv.azurewebsites.net).
  • JWT issued for the audience (099153c2625149bc8ecb3e85e03f0022) only.

Conclusion

Using signed JSON Web Tokens facilitates and standardize the way of separating the Authorization server and the Resource server, no more need for unifying machineKey values nor having the risk of sharing the “decryptionKey” and “validationKey” key values among different Resource servers.

Keep in mind that the JSON Web Token we’ve created in this tutorial is signed only, so do not put any sensitive information in it :)

The source code for this tutorial is available on GitHub.

That’s it for now folks, hopefully this short walk through helped in understanding how we can configure the Authorization Server to issue JWT and how we can consume them in a Resource Server.

If you have any comment, question or enhancement please drop me a comment, I do not mind if you star the GitHub Repo too :)

Follow me on Twitter @tjoudeh

References

The post JSON Web Token in ASP.NET Web API 2 using Owin appeared first on Bit of Technology.


Darrel Miller: Add Runscope logging to your ASP.NET Web API in minutes

If you are building an ASP.NET Web API and want a view into the HTTP traffic that is hitting your API then this is a really quick solution that might prove useful.

Monitoring

Runscope is a cloud based service that allows you to monitor, measure and test Web APIs.  By using their API I was able to build a HttpMessageHandler that logs all requests and responses to the service.  Runscope has a free tier that allows you to log 10K requests/month.

Add a messagehandler

In your Web API project, simply add the Nuget package Runscope.HttpMessageHandler and the following line of code in your Web API configuration code:

config.MessageHandlers.Add(new RunscopeApiMessageHandler(<ApiKey>,<BucketKey>);

You can get an APIKey by creating an Application within Runscope and the bucket key is displayed at the bottom right hand corner of the page.

And you’re done.

Get results immediately

Once you start making requests to the API you will be able to see the details of the request in the Runscope Traffic Inspector,

RunscopeRequest

and the response…

RunscopeResponse

Let me show you how

The following demonstrates how to create a Web API, setup a Runscope account and add Runscope logging to it in less than 5 mins.

Image credits : Heart rate monitor https://flic.kr/p/8S3ofm 
Image credits : Stopwatch https://flic.kr/p/6xSoka


Ali Kheyrollahi: Performance Series - How poor performance of HttpContent.ReadAsAsync can affect your API/site

Level [T2]

This has been a revelation - what I am about to reveal here, deeply surprised me - it might surprise you too. This post is mainly about consuming restful APIs using HttpClient and when the payload is JSON.

UPDATE: I got in touch with the ASP.NET team and they confirmed this as a performance bug which has now been fixed but the fix yet not available.

As you probably know performance and benchmarking is very close to my heart and I have been recently focusing on benchmarking a few APIs at work. One of my observations was that the Web APIs/Web Sites which have historically been IO-bound, they show sign of CPU strain and have become CPU-bound.

When you think logically about it, there is no magic here: by using async/await, you end up putting your CPU into some use unlike the old times when the threads are blocked waiting for the IO to return and CPU would be twiddling its thumb. However, I found the CPU overhead of the operations excessive so I set out to benchmark a few different scenarios.

Test Setup

Two APIs were created where one was using the other. These two APIs were part of the same cloud service which was deployed to two separate Medium (A2) web roles. I used 2 different deployments of the same code, one dependent upon version 4.0.30506.0 of the API and the ther one with the latest version which was 5.2.2. Difference between two versions of the Web API is the topic of another post, but the differences were not huge although newer versions showed improved performance.

API being called returns a customer with its orders. Every customer has between 1 to 3 orders and each order between 1-3 items. On the long run, these randomisation gets evened out. Each document returned is between 1-2 KB. So the more superficial API, for every customer, makes one call to get the customer and for each customer will separately call the deeper API once for each order. Then it combines the result and sends back the response. Both APIs are deployed in the same Azure Data Centre.

You can find the whole code at GitHub. The code takes 4 different approaches as below:

public class CustomerController : ApiController
{
public FullCustomer GetSync(int id)
{
var webClient = new WebClient();
var customerString = webClient.DownloadString(BuildUrl(id));
var customer = JsonConvert.DeserializeObject<Customer>(customerString);
var fullCustomer = new FullCustomer(customer);
var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
var orderString = webClient.DownloadString(BuildUrl(id, orderId));
var order = JsonConvert.DeserializeObject<Order>(orderString);
orders.Add(order);
}
fullCustomer.Orders = orders;
return fullCustomer;
}

public async Task<FullCustomer> GetASync(int id)
{
var webClient = new WebClient();
var customerString = await webClient.DownloadStringTaskAsync(BuildUrl(id));
var customer = JsonConvert.DeserializeObject<Customer>(customerString);
var fullCustomer = new FullCustomer(customer);
var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
var orderString = await webClient.DownloadStringTaskAsync(BuildUrl(id, orderId));
var order = JsonConvert.DeserializeObject<Order>(orderString);
orders.Add(order);
}
fullCustomer.Orders = orders;
return fullCustomer;
}

public async Task<FullCustomer> GetASyncWebApi(int id)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var responseMessage = await httpClient.GetAsync(BuildUrl(id));
var customer = await responseMessage.Content.ReadAsAsync<Customer>();
var fullCustomer = new FullCustomer(customer);
var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
responseMessage = await httpClient.GetAsync(BuildUrl(id, orderId));
var order = await responseMessage.Content.ReadAsAsync<Order>();
orders.Add(order);
}
fullCustomer.Orders = orders;
return fullCustomer;
}

public async Task<FullCustomer> GetASyncWebApiString(int id)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var responseMessage = await httpClient.GetAsync(BuildUrl(id));
var customerString = await responseMessage.Content.ReadAsStringAsync();
var customer = JsonConvert.DeserializeObject<Customer>(customerString);
var fullCustomer = new FullCustomer(customer);
var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
responseMessage = await httpClient.GetAsync(BuildUrl(id, orderId));
var orderString = await responseMessage.Content.ReadAsStringAsync();
var order = JsonConvert.DeserializeObject<Order>(orderString);
orders.Add(order);
}
fullCustomer.Orders = orders;
return fullCustomer;
}

private string BuildUrl(int customerId, int? orderId = null)
{
string baseUrl = string.Format("http://{0}:8080/api/customer/{1}", Request.RequestUri.Host, customerId);
return orderId.HasValue
? string.Format("{0}/order/{1}", baseUrl, orderId.Value)
: baseUrl;
}

}
So as you can see, we use 4 different methods:

1) Using WebClient in the sync fashion
2) Using WebClient in the async fashion
3) Using HttpClient in the async fashion with ReadAsAsync on HttpContent
4) Using HttpClient in the async fashion with reading content as string and then using JsonConvert to deserialise

I used SuperBenchmarker to invoke the main API which gathers the data from the other API. I used the tool within the same Azure Data Centre from another machine (none of the APIs) to make the tests more realistic yet eliminate network idiosyncrasies.

I used 5000 requests with concurrency of 10 - although I tried other number as well which did not make any material difference in the results.

Results

Here is the result for scenario 1 (sync using WebClient):

TPS:    394 (requests/second)
Max: 199ms
Min: 8ms
Avg: 25ms

50% below 24ms
60% below 25ms
70% below 27ms
80% below 28ms
90% below 30ms
95% below 32ms
98% below 36ms
99% below 55ms
99.9% below 185ms


The result for scenario 2 (Async using WebClient) usually shows better throughput but higher CPU

TPS:    485 (requests/second)
Max: 291ms
Min: 5ms
Avg: 20ms

50% below 19ms
60% below 21ms
70% below 23ms
80% below 25ms
90% below 27ms
95% below 29ms
98% below 32ms
99% below 36ms
99.9% below 284ms

The CPU difference is not huge and can be explained by the increase throughput:

CPU usage during Scenario 1 and 2

Now what surprised me greatly was the result of the third scenario (using HttpContent.ReadAsAsync<T>). Apart from CPU of 100% and signs of queueing, here is the result:

TPS:    41 (requests/second)
Max: 12656ms
Min: 26ms
Avg: 240ms

50% below 170ms
60% below 178ms
70% below 187ms
80% below 205ms
90% below 256ms
95% below 296ms
98% below 370ms
99% below 3181ms
99.9% below 12573ms

Yeah, shocking. The diagram below compares CPU usage between scenario 1 and 3:

CPU usage in scenario 1 (arrow) and 3 (box)

Scenario 4 is definitely better and is not too far from scenario 1 and 2:

TPS:    230 (requests/second)
Max: 7068ms
Min: 7ms
Avg: 43ms

50% below 20ms
60% below 22ms
70% below 24ms
80% below 26ms
90% below 29ms
95% below 34ms
98% below 110ms
99% below 144ms
99.9% below 7036ms

The CPU usage is around 80% and definitely worse that scenario 1 and 2 (which requires further analysis).

Analysis

Where is the problem? It appears that JSON Deserialization when reading from a stream is not efficient. It is possible that the JSON Deserialization has to optimise for memory efficiency rather than CPU efficiency since when the whole string is passed, it is surely much faster. 

Profiling proves that the problem is indeed JSON Deserialization:

Profiling scenario 3 is showing that the most of the CPU time is spent in JSON Deserialisation

So in order to prove that, we do not have to invoke an API. The whole operation can be done inside a Console application. So I used the same code that was generating customers and orders. Here I am comparing

private static void Main(string[] args)
{
const int TotalRun = 10*1000;

var customerController = new CustomerController();
var orderController = new OrderController();
var customer = customerController.Get(1);

var orders = new List<Order>();
foreach (var orderId in customer.OrderIds)
{
orders.Add(orderController.Get(1, orderId));
}

var fullCustomer = new FullCustomer(customer)
{
Orders = orders
};

var s = JsonConvert.SerializeObject(fullCustomer);
var bytes = Encoding.UTF8.GetBytes(s);
var stream = new MemoryStream(bytes);
var content = new StreamContent(stream);

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");


var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < TotalRun+1; i++)
{
var a = content.ReadAsAsync<FullCustomer>().Result;
if(i % 100 == 0)
Console.Write("\r" + i);
}
Console.WriteLine();
Console.WriteLine(stopwatch.Elapsed);

stopwatch.Restart();
for (int i = 1; i < TotalRun+1; i++)
{
var sa = content.ReadAsStringAsync().Result;
var a = JsonConvert.DeserializeObject<FullCustomer>(sa);
if (i % 100 == 0)
Console.Write("\r" + i);
}
Console.WriteLine();
Console.WriteLine(stopwatch.Elapsed);

Console.Read();

}

As expected, the result shows uncomparable difference, in the order of ~120:

10000
00:00:06.2345493
10000
00:00:00.0509763

So this result basically confirms what we have seen. I will get in touch with James Newton King and try to shed more light on the subject.

Conclusion

HttpContent.ReadAsAsync on JSON payloads is really slow - in the order of 120x compared to JsonConvert. I guess it might to do with the memory efficiency of reading from streams (keeping memory footprint at zero)  but that is a guess and I have been in touch with James Newton King (creator of Json.Net) to get to the bottom of it.

For the meantime, if you know your content is not going to be huge and always in JSON, you might as well forget about content negotiation and read it as a string and then use JsonConvert to deserialize.


Radenko Zec: Manual JSON serialization from DataReader in ASP.NET Web API

In one of my previous blog posts 8 ways to improve ASP.NET Web API performance I talked how we’ve used manual JSON serialization from DataReader to gain some performance benefits.

I haven’t provided any code example, but only link to this excellent blog post from Rick Strahl JSON serialization of a DataReader.

In our production project we’ve used code from Rick Strahl’s blog post to do this.

Instead reading values from DataReader and populating objects and after that reading again values from those objects and producing JSON using some JSON Serializer,  we can directly create a JSON string from DataReader and avoid unnecessary creation of objects.

I’ve received lots of requests to explain this method on my blog.

JsonSerialization

Set up JSON serialization project

As I mention above we’ve used WestWind’s code to do this.

However, this library which is used to perform JSON Serialization is quite large and contains a lot of code that we didn’t need.

So I’ve just extracted the code related to JSON serialization and modified it a little bit to support additional data type and to serialize in CamelCase.

We have also removed some data types we didn’t need.

You can download this modified project library here.

How to use this library

Code for serialization from DataReader to JSON string is very small.

We just need to call the Serialize method and pass the instance of DataReader we want to serialize.

string jsonResult;
var serializer = new WestwindJsonSerializer
{
     DateSerializationMode = JsonDateEncodingModes.Iso
};

using (SqlDataReader reader = cmd.ExecuteReader())
{ 
     jsonResult = serializer.Serialize(reader);
}

 

How to implement this in your ASP.NET Web API controller method

We have implemented code above in our Repository method GetItemsAsJson which is used for retrieving items from database.

The code looks similar to this.

public HttpResponseMessage GetItems([FromUri]ItemQueryParams itemQueryParams)
{

var jsonResult = this.itemRepository.GetItemsAsJson(itemQueryParams);
if (!string.IsNullOrEmpty(jsonResult))
{
     var response = Request.CreateResponse(HttpStatusCode.OK);
     response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");
     return response;
}
...
...
}

 

If you like this article don’t forget to subscribe to this blog and make sure you don’t miss new upcoming blog posts.

 

The post Manual JSON serialization from DataReader in ASP.NET Web API appeared first on RadenkoZec blog.


Ali Kheyrollahi: SuperBenchmarker v0.4 released

Level [T2]

This is a quick shoutout on the release of version 0.4 of SuperBenchmarker, a Web and/or Web API performance benchmarking command line tool for Windows.

You might have heard about and used Apache Benchmark (ab.exe) in the past which is a very useful tool but on Windows it is very limited (e.g cannot make POST, PUT, etc requests and only supports GET). SuperBenchmarker (sb.exe) supports PUT, DELETE, POST or any arbitrary method and allows you to parameterise the URL and headers using a data file, a .NET DLL plugin and the new feature is the randomisation feature which removes the need for any setup when all needed is random data.


Getting started

The best way to get SuperBenchmarker is to use awesome Chocolatey which is Windows' equivalent of apt-get tool on Linux.

To get Chocolatey, just run this command in your Powershell console (in Administrative mode):
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))
And then install SuperBenchmarker in the command line shell:
c:\> cinst SuperBenchmarker
And now you are ready to load test:
c:\> sb -u http://google.com
Note: if you are using Visual Studio's command line shell, you cannot use ampersand character (&) and you have to escape it using hat (^).

Using SuperBenchmarker

Normally you would define total number of requests and concurrency:
c:\> sb -u http://google.com -c 10 -n 2000
Statement above runs 2000 requests with concurrency of 10. At the end, you are shown important metrics of the test:
Status 503:    1768
Status 200: 232

TPS: 98 (requests/second)
Max: 11271.1890515802ms
Min: 3.15724613377097ms
Avg: 497.181240820346ms

50% below 34.0499543844287ms
60% below 41.8178295863705ms
70% below 48.7612961478952ms
80% below 87.4385213898198ms
90% below 490.947293319644ms
So the breakdown of the statuses returned, TPS (transaction per second), minimum, maximum and average of the time taken. But more importantly, your percentiles that really should be driving your performance SLAs (90% or 99%). [Never use the average for anything].

In case you need to dig deeper, a log file gets created in the current directory with the name run.log which you can change using -l parameter:
c:\> sb -u http://google.com -c 10 -n 2000 -l c:\temp\mylog.txt
log file is a tab separated file which contains these columns: order number (based on the time started not the time ended), status code, time taken in ms and then any custom parameters that you might have had - see below.

Sometimes when running a test for the first time, something might not have been quite right in which case you can make a dry run/debug using -d parameter that makes a single request and the body of the response will be shown at the end. If you want to see the headers as well, use -h parameter.
c:\> sb -u http://google.com -c 10 -n 2000 -d -h

Supplying request headers or a payload for POST, PUT and DELETE

In order to pass your tailored request headers, a template file needs to be defined which is basically the HTTP request template (minus the first line defining verb and URL and version):
c:\> sb -u http://google.com -t template.txt
And the template.txt contains our custom headers (from the second line of the HTTP request):
User-Agent: SuperBenchmarker
MyCustomHeader: foo-bar;baz=biz
Please note that you don't have to provide headers such as Host and Content-Length - in fact it will raise errors. These headers will be automatically added by the underlying framework.

For using POST, PUT and DELETE we need to supply the verb parameter:
c:\> sb -u http://google.com -v POST
But this request would require a payload as well which we need to supply. We use the template file to supply HTTP payload as well as any headers. Similar to an HTTP request, there must be an empty line between headers and body:
User-Agent: WhateverValueIWant
Content-Type: x-www-formurlencoded

name=value&age=25

Parameterising your requests

Basically you can parameterise your requests using a CSV file containing values, your plugin DLL or by specifying randomisation.

You would define parameters in URL and headers (payload not yet supported but coming soon in 0.5) using SuperBenchmarker's syntax:
{{{MyParameter}}}
As you can see, we use three curly brackets to denote a parameter. For example the statement below defines a customerId parameter:
c:\> sb -u "http://myserver.com/api/customer?customerid={{{customerId}}}^&ignore=false"
Please note quoting the URL and use of ^ to escape & character - if you are using Visual Studio command prompt. To run the test successfully, you need to provide a CSV file containing customerId:
customerId
123,
245,
and use -f option to run the test:
c:\> sb -u "http://myserver.com/api/customer?customerid={{{customerId}}}&ignore=false" -f c:\mypath\values.csv
Alternatively, you can use a plugin DLL to provide values:
c:\> sb -u "http://myserver.com/api/customer?customerid={{{customerId}}}&ignore=false" -p c:\mypath\myplugin.dll
This DLL must have a single public class implementing IValueProvider interface which has a single method:
public interface IValueProvider
{
IDictionary<string, object> GetValues(int index);
}
For every request implementation of the interface is called and the index of the request is passed to and in return a dictionary of field names with their respective values is passed back.

Now we have a new feature that in most cases alleviates the need for CSV file or plugin and that is the ability to setup random value provider in the definition of the parameter itself:
c:\> sb -u "http://myserver.com/api/customer?customerid={{{customerId:RAND_INTEGER:[1000:2000]}}}&ignore=false"
The parameter above is set up to be filled by a random integer between 1000 and 2000.
Possible value types are:
  • String: using RAND_STRING. Will output random words
  • Date: using RAND_DATE (accepts range)
  • DateTime: using RAND_DATETIME (accepts range)
  • DateTimeOffset: using RAND_DATETIMEOFFSET which outputs ISO dates (accepts range)
  • Double: using RAND_DOUBLE (accepts range)
  • Name: using RAND_NAME. Will output random names

Feedback

Don't forget to feedback with issues and feature requests in the GitHub page. Happy load testing!


Darrel Miller: Xamarin Evolve

This past week I spent in Atlanta, Georgia, attending Xamarin Evolve and Atlanta Code Camp.  This was the second annual Evolve conference and attendance went from 600 the first year to 1200 this year.  This year’s event was an impressive affair.

WP_20141010_001

Cultivating an Niche

Not only did the number of attendees grow significantly from last year, there were 700 of those people who attended the pre-conference training sessions.  This is a significant amount of demand for what is perceived by some to be a fairly expensive set of tools to build cross-platform native mobile applications.

As Mike Beverly notes, Xamarin are making the transition from a place where C# .Net developers go to create iOS and Android versions of their applications, to a cross platform solution for developers of all platforms who are prepared to learn C# and .net.

The idea that you can build mobile applications that have the look and feel of the native platform, but share a significant chunk of client code between platforms is a lofty goal.  One that Xamarin seem to be making significant progress towards.

Building a Community

Numerous people have made comparison between the atmosphere at the Evolve event and Microsoft PDC’s of the past.  There is no doubt there was a palpable excitement in the air.

There was a sensation that Xamarin was going all out to make sure that attendees got everything they possibly could out of the event.  Xamarin employees were everywhere and highly visible due to them all wearing the same shirts.  Attendees could schedule one on one meetings to discuss projects and ask questions.  The Darwin Lounge was full of toys and challenges to give developers the chance to explore all kinds of cool things.

The technical production of the event, the food and drinks, the social events, the venue, were all quite spectacular.   This holistic focus on quality is what makes developers want to be  part of the community.  It feels safe.  It feels like it will have a future. 

WP_20141009_001We as developers are tired of half finished products being thrown over the wall at us by vendors;  those products being milked dry once they become successful and then left to rot when the next cool thing comes along. 

When you eat the locally made fruit popsicle and find some Xamarin inspired pun printed on the popsicle stick, you want to believe that the same attention to detail is going into the products.

Heading in the right direction

While preparing for my talk at Evolve I took the opportunity to write some sample applications and test some of my OSS PCL libraries on various platforms.  I was impressed that my libraries worked unchanged on Android.  Creating simple applications that worked on multiple platforms was quite straightforward once I had figured out how to setup the Android Emulator.

Xamarin have recognized the pain of using the Android SDK for development and announced the release of their own Android player that not only makes setup and configuration way easier, but it is also significantly faster than Google’s own emulator.

In the opening keynote, there were a number of other significant product announcements.  The Sketches tool provides an instant feedback mechanism to write code and see it immediately appear on apps running on iOS and Android emulators.  This high speed feedback loop is the kind of feature that Web Browser and HTML/CSS advocates have been rubbing in the face of native developers for years.

The Insights real-time monitoring product and new features in Test Cloud demonstrate Xamarin’s desire to get developers to produce high quality apps with their toolset.  This is a far cry from Microsoft’s efforts to evangelize the Windows Phone where the marketing department seem to be focused on the quantity of apps in the app store with little care for quality.

Architecture is important

Regardless of all the delightful trimmings that VC funded companies are able to display, when it comes down to it, architecture is a key component to longevity.  Native user interface will always have a performance edge over a generalized user interface solution.  In the past, cross-platform issues and development speed were barriers that made native development a barrier to many.  Xamarin is lowering that barrier.

As someone who has always been a believer in native user experiences, I really hope to see many more editions of Evolve in the future.


Taiseer Joudeh: Two Factor Authentication in ASP.NET Web API & AngularJS using Google Authenticator

Last week I was looking on how to enable Two Factor Authentication in a RESTful ASP.NET Web API service using Soft Tokens not SMS. Most of the examples out there show how to implement this in MVC application where there will be some cookies transmitted between requests, this approach defeats the stateless nature of the RESTful APIs, as well most of the examples ask for the passcode on the login form only, so there was no complete example on how to implement TFA in RESTful API.

The live AngularJS demo application is hosted on Azure, the source code for this tutorial on GitHub.

Basically the requirements I needed to fulfill in the solution I’m working on are the following:

  • The Web API should stay stateless, no cookies should be transmitted between the consumer and the API.
  • Each call to the Web API should be authenticated using OAuth 2.0 Bearer tokens as we implemented before.
  • Two Factor Authentication is required only for some sensitive API requests, in other words for some selective sensitive endpoints (i.e. transfer money) should ask for Two Factor Authentication time sensitive passcode along with the valid bearer access token, and the other endpoints will use only One Factor for authentication which is the OAuth 2.0 bearer access tokens only.
  • We need to build cost effective solution, no need to add new cost by sending SMSs which contain a passcode,  we will depend on our users’ smartphones as a Soft Token. The user needs to install Google Authenticator application on his/her smartphone which will generate a time sensitive passcode valid for only 30 seconds.
  • Lastly the front-end application which will consume this API will be built using AngularJS and should support displaying QR codes for the Preshared key.

TFA Featured Image

Before jumping into the implementation I’d like to emphasize some concepts to make sure that we understand the core components of Two Factor Authentication and how Google Authenticator works as Soft Token.

What is Two Factor Authentication?

Any user trying to access a system can be authenticated by one of the below ways:

  1. Something the user knows (Password, Secret).
  2. Something the user owns (Mobile Phone, Device).
  3. Something the user is (Bio-metric, fingerprint).

Two Factor authentication is a combination of any two of the above three ways. When want to apply this to real business world applications, we usually use the first and the second ways. This is because the third way (Biometrics) is very expensive and complicated to roll out, and the end user experience can be problematic.

So Two Factor authentication is made up of something that the user knows and another thing the user owns. The smartphone is something the user owns so receiving a passcode (receiving SMS or call) on it, or generating a passcode using the smartphone (as in our case) will allow us to add Two Factor authentication.

In our Back-end API we’ll ask the user to provide the below two separate factors when he/she wants to access a sensitive endpoint, the factors the user should provide are:

  1. The OAuth 2.0 bearer access tokens which is granted to the user when he provides his/her username and password at an earlier stage.
  2. The time sensitive passcode generated on the user smartphone which he/she owns using Google Authenticator.

What is Google Authenticator?

Google Authenticator is a mobile based application which is available on different platforms, the application works as a soft token which is responsible for generating time sensitive passcodes which will be used to implement Two Factor authentication for Google services. Basically the time sensitive passcode generated contains six digits which is valid for 30 seconds only, then new six digits will be generated directly.

Once you install the Google Authenticator application on your smartphone, it will basically ask you to enter Preshared Secret/Key between you and the application, this Preshared Key will be generated from our back-end API for each user register in our system and will be displayed on the UI as QR code or as plain text so the user can add this Preshared Key to Google Authenticator. More about generating this Preshared Key later in this post.

The nice thing about Google Authenticator is that it generates the time sensitive passcode on the smartphone without depending on anything, there is no need for internet connection or access to Google services to generate this passcode. How is this happening? Well the Google Authenticator implements Time-based One-time Password Algorithm (TOTP) which is an algorithm that computes a one-time password from a shared secret key and the current time, TOTP is based on HMAC-based One Time Password algorithm (HOTP) with a time-stamp replacing the incrementing counter in HOTP. You can check the implementation for Google Authenticator here.

Google Authenticator

In our solution the first step to authenticate the user is by providing his username and password in order to obtain an OAuth 2.0 bearer access token which is considered a type of knowledge-factor authentication, then as we agreed before and for certain selective sensitive API end-points (require second factor authentication), the user will open Google Authenticator application installed on his/her smartphone, lookup the time sensitive passcode which is generated from the Preshared key, and this passcode represents something the user owns (represents ownership-factor authentication).

Process flow for using Google Authenticaor with our Back-end API

In this section I’ll show you the process flow which the user will follow in our Two Factor authentication enabled solution in order to allow the user to access the selective sensitive API end-points.

  • The user will register in our-back end system by providing username,password and confirm password (normal registration process), upon successful registration and in the back-end API,  a Preshared Key (PSK) is generated for this user and returned to the UI in form of QR code and plain text (5FDAEHNBNM6W3L2S) so the user will open Google Authenticator application installed on his smartphone and scan this Preshared Key or enter it manually and select Time Based key. UI will look as the image below:

TFA Signup Form

  • Now the user will login to our system by providing his username/password and obtaining an OAuth 2.0 access token which will allow him to access our protected API resources, as long as he is trying to access non elevated sensitive end-point (i.e. transfer money) then our back-end API will be happy with only the one-factor authentication (knowledge-based factor) which is the OAuth 2.0 bearer access token only. As on the images blow the user is allowed to access his transactions history (non sensitive end point, yet it is protected by one-factor authentication).

Login

Transactions History

  • Now the user wants to perform an elevated sensitive request (Transfer Money), this end-point in out back-end API is configured to ask for second ownership factor to authenticate before completing the request, so the UI will ask the user to enter the time sensitive pass-code provided by Google Authenticator, the UI for Transfer Money will look as below:

Transfer Money TFA Code

  • The user will fill the form with the details he wants, if he tried to issue a transfer request without providing the second factor authentication (pass code) the request will be rejected and HTTP 401 unauthorized will be returned because this endpoint is sensitive and needs a second ownership factor to authenticate successfully. So the user will grab his smartphone, open Google Authenticator application and type the six digits pass code appears that on the application and hit transfer button. This six digits code will be sent in a custom HTTP header along with the OAuth 2.0 access token to this sensitive end-point.

Google Authenticator Passcode

  • Now the API receives this pass code for example (472307), and checks the code validity, if it is valid then the API will process the request and the user will complete transferring the money successfully (execution for the sensitive end-point is successful).

Money Transfer Successfully

The last step is the trickiest one, you are not asking yourself how this six digits code generated by Google Authenticator which will keep changing every 30 seconds will be understood and considered authentic by our back-end API. To answer this we need to take a brief look on how Google Authenticator produces those six digits; because we’ll simulate the same procedure at our back-end API.

How does Google Authenticator work?

As we have stated before Google Authenticator supports both TOTP algorithm on top of HOTP algorithm for generating onetime pass-codes or time sensitive pass-codes.

The idea behind HOTP is that the server (our back-end API) and client (Google Authenticator app) share a Preshared Key value and a counter, The preshared key and the counter are used to compute a one-time passcode independently on both sides (Notice it is a one-time passcode not a time sensitive passcode). Whenever a passcode is generated and used, the counter is incremented on both sides, allowing the server and client to remain in sync.

TOTP is built on top of HOTP, it uses HOTP same algorithm with one clear difference; the counter used in TOTP is replaced by the current time. But the challenge here is that this six digits passcode will keep changing rapidly with every second change and this will not be feasible because the end user will not be able to enter this number when asked for.

To solve this issue we’ll generate the number (counter) corresponding to 00 second of the current minute and let it remain constant for the next 30 seconds; by doing this the six digits passcode will become usable and will stay constant for the next 30 seconds. Note that all time calculations are based on UTC, so there is no need to worry about the time zone for the server and the time zone for the user using Google Authenticator application.

When the sensitive API endpoint receives this time sensitive passcode, it will repeat the process described above. Basically the API will know the user id from the OAuth access token sent, then fetch the Preshared key saved in the database for this user, and from there it will generate the time sensitive passcode and compare it with the passcode sent from the client application (UI), if the passcode sent form the UI matches the one generated in the back-end API then the API will consider this passcode authentic and process the request successfully.

Note: One of the greatest books which describes how Google Authenticator works is Pro ASP.NET Web API Security (Chapter 14) written by Badrinarayanan Lakshmiraghavan. Highly recommend if you are interested in ASP.NET Web API security in general.

Now it is time to start implementing this solution, this is the longest theory I’ve written so far in all my blog posts so we’d better to move to the code :)

Building the Back-End API

I highly recommend to read my previous post Token Based Authentication before implementing the steps below and enabling Two Factor Authentication, because the steps mentioned below are very identical to the previous post, so I’ll list the identical steps and will be very brief in explaining what each step is doing except for the new steps which are related to enabling Two Factor Authentication in our back-end API.

Step 1: Creating the Web API Project

Create an empty solution and name it “TFAWebApiAngularJS” then add a new ASP.NET Web application named “TwoFactorAuthentication.API”, the selected template for the project will be “Empty” template with no core dependencies. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Step 2: Installing the needed NuGet Packages:

Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Cors -Version 3.0.0
Install-Package Microsoft.Owin.Security.OAuth -Version 3.0.0
Install-Package Microsoft.AspNet.Identity.Owin -Version 2.0.1
Install-Package Microsoft.AspNet.Identity.EntityFramework -Version 2.0.1

Step 3: Add Owin “Startup” Class

Right click on your project then add a new class named “Startup”. It will contain the code below:

public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);

        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            OAuthBearerAuthenticationOptions OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                //For Dev enviroment only (on production should be AllowInsecureHttp = false)
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider = new SimpleAuthorizationServerProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);

            //Token Consumption
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

        }
    }

Basically this class will configure our back-end API to use OAuth 2.0 bearer tokens to secure the endpoints attribute with [Authorize] attribute, as well it also set the access token to expire after 24 hours. We’ll implement the class “SimpleAuthorizationServerProvider” in later steps.

Step 4: Add “WebApiConfig” class

Right click on your project, add a new folder named “App_Start”, inside this class add a class named “WebApiConfig”, then paste the code below:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }

Step 5: Add the ASP.NET Identity System

Now we’ll configure our user store to use ASP.NET Identity system to store the user profiles, to do this we need a database context class which will be responsible for communicating with our database, so add a new class and name it “AuthContext” then paste the code snippet below:

public class AuthContext : IdentityDbContext<ApplicationUser>
    {
        public AuthContext()
            : base("AuthContext")
        {
        }
    }

    public class ApplicationUser : IdentityUser
    {
        [Required]
        [MaxLength(16)]
        public string PSK { get; set; }
    }

As you see in the code above, the “AuthContext” class is inheriting from “IdentityDbContext<ApplicationUser>”, where the “ApplicationUser” inherits from “IdentityUser”, this is done like this because we need to extend the “AspNetUsers” table and add a new column named “PSK” which will contain the Preshared key generated for this user in our back-end API. More on generating this Preshared key later in the post.

Now we want to add “UserModel” which contains the properties needed to be sent once we register a user, this model is a POCO class with some data annotations attributes used for the sake of validating the registration payload request. So add a new folder named “Models” then add a new class named “UserModel” and paste the code below:

public class UserModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

Now we need to add a new connection string named “AuthContext” in our Web.Config file, so open you web.config and add the below section:

<connectionStrings>
    <add name="AuthContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=TFAAuth;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so adda  new class named “AuthRepository” and paste the code snippet below:

public class AuthRepository :IDisposable    
    {
        private AuthContext _ctx;

        private UserManager<ApplicationUser> _userManager;

        public AuthRepository()
        {
            _ctx = new AuthContext();
            _userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_ctx));
        }

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
            ApplicationUser user = new ApplicationUser
            {
                UserName = userModel.UserName,
                TwoFactorEnabled = true,
                PSK = OneTimePass.GenerateSharedPrivateKey()
            };

            var result = await _userManager.CreateAsync(user, userModel.Password);

            return result;
        }

        public async Task<ApplicationUser> FindUser(string userName, string password)
        {
            ApplicationUser user = await _userManager.FindAsync(userName, password);
            
            return user;
        }

        public void Dispose()
        {
            _ctx.Dispose();
            _userManager.Dispose();

        }
    }

By looking at the code above you will notice that we are generating Preshared key for the registered user by calling the static method “OneTimePass.GeneratePresharedKey”, this Preshared key will be sent back to the end user so he will enter this 16 characters key in his Google Authenticator application.

Step 7: Add support for generating Preshared keys and passcodes

Note: There are lot of implementations for Google Authenticator algorithms (HOTP, and TOTP) out there in different platforms including .NET, but there is nothing that beats Badrinarayanan Lakshmiraghavan’s implementation in simplicity and minimal number of code used. The implementation exists and is available for public in the companion source code which comes with his Pro ASP.NET Web API Security book, so all the credit for the below implementation goes for Badrinarayanan, and I’ll not re-explain how the implementation is done. Badrinarayanan explained it in a very simple way, so my recommendation is to check his book.

So add a new folder named “Services” and inside it add a new file named “TimeSensitivePassCode.cs” then paste the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Text;

namespace TwoFactorAuthentication.API.Services
{
    public static class TimeSensitivePassCode
    {
        public static string GeneratePresharedKey()
        {
            byte[] key = new byte[10]; // 80 bits
            using (var rngProvider = new RNGCryptoServiceProvider())
            {
                rngProvider.GetBytes(key);
            }

            return key.ToBase32String();
        }

        public static IList<string> GetListOfOTPs(string base32EncodedSecret)
        {
            DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc);

            long counter = (long)Math.Floor((DateTime.UtcNow - epochStart).TotalSeconds / 30);
            var otps = new List<string>();

            otps.Add(GetHotp(base32EncodedSecret, counter - 1)); // previous OTP
            otps.Add(GetHotp(base32EncodedSecret, counter)); // current OTP
            otps.Add(GetHotp(base32EncodedSecret, counter + 1)); // next OTP

            return otps;
        }

        private static string GetHotp(string base32EncodedSecret, long counter)
        {
            byte[] message = BitConverter.GetBytes(counter).Reverse().ToArray(); //Intel machine (little endian) 
            byte[] secret = base32EncodedSecret.ToByteArray();

            HMACSHA1 hmac = new HMACSHA1(secret, true);

            byte[] hash = hmac.ComputeHash(message);
            int offset = hash[hash.Length - 1] & 0xf;
            int truncatedHash = ((hash[offset] & 0x7f) << 24) |
            ((hash[offset + 1] & 0xff) << 16) |
            ((hash[offset + 2] & 0xff) << 8) |
            (hash[offset + 3] & 0xff);

            int hotp = truncatedHash % 1000000; 
            return hotp.ToString().PadLeft(6, '0');
        }
    }

    public static class StringHelper
    {
        private static string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";

        public static string ToBase32String(this byte[] secret)
        {
            var bits = secret.Select(b => Convert.ToString(b, 2).PadLeft(8, '0')).Aggregate((a, b) => a + b);

            return Enumerable.Range(0, bits.Length / 5).Select(i => alphabet.Substring(Convert.ToInt32(bits.Substring(i * 5, 5), 2), 1)).Aggregate((a, b) => a + b);
        }

        public static byte[] ToByteArray(this string secret)
        {
            var bits = secret.ToUpper().ToCharArray().Select(c => Convert.ToString(alphabet.IndexOf(c), 2).PadLeft(5, '0')).Aggregate((a, b) => a + b);

            return Enumerable.Range(0, bits.Length / 8).Select(i => Convert.ToByte(bits.Substring(i * 8, 8), 2)).ToArray();
        }

    }
}

Briefly what we’ve implemented in this class is the below

  • We’ve added a static method named “GeneratePresharedKey” which is responsible for generating 16 characters as our Preshared key, basically it is an array of 80 bit which is encoded using base32 format, this base32 format uses 26 letters A-Z and six digits 2-7 which will produce restricted set of characters that can be conveniently used by end users.
  • Why did we encod the key using base32 format? Because Google Authenticator uses the same encoding to help end users who prefer to enter the Preshared key manually without any confusion, the numbers which might confuse the users with letters are omitted (i.e 0,1,8,9). The implementation for Base32 encoding can be found on the extension method named “ToBase32String” in the helper class “StringHelper”.
  • We’ve implemented the static method “GetHotp” which accepts the base32 encoded Preshared key (16 characters) and a counter, this method will be responsible for generating the One time passcodes.
  • As we stated before the implementation of TOTP is built on top of HOTP, the only major difference is that the counter is replaced by time, so in the method “GetListOfOTPs” we are getting three time sensitive pass codes, one in the past, another in the present, and one in the future; the reason for doing this is to accommodate for the clock alter/shift between the server time and the clock on the smartphone where the passcode is generated using Google Authenticator, we are basically making it easy for the end user when he enters the time sensitive passcodes.

Step 8: Add our “Account” Controller

Now we’ll add a Web API controller which will be used to register a new users, so under add new folder named “Controllers” then add an Empty Web API 2 Controller named “AccountController” and paste the code below:

[RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private AuthRepository _repo = null;

        public AccountController()
        {
            _repo = new AuthRepository();
        }

        // POST api/Account/Register
        [AllowAnonymous]
        [Route("Register")]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = await _repo.RegisterUser(userModel);
            
            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }

            ApplicationUser user = await _repo.FindUser(userModel.UserName, userModel.Password);

            return Ok(new { PSK = user.PSK });
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _repo.Dispose();
            }

            base.Dispose(disposing);
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }
    }

It is worth noting here that inside method “Register” we’re returning the SPK after registering the user successfully, this PSK will be displayed on the UI on form of QR code and plain text so we give the user 2 options to enter it in Google Authenticator.

Step 9: Add Protected Money Transactions Controller with Two Actions

Now we’ll add a protected controller which can be accessed only if the request contains valid OAuth 2.0 bearer access token, inside this controller we’ll add 2 action methods, one of those action methods “GetHistory” will only requires One-Factor authentication (only bearer tokens) to process the request, on the other hand there will be another sensitive action method named “PostTransfer” which will require Two Factor authentication to process the request.

So add new Web API controller named “TransactionsController” under folder Controllers and paste the code below:

[Authorize]
    [RoutePrefix("api/Transactions")]
    public class TransactionsController : ApiController
    {
        [Route("history")]
        public IHttpActionResult GetHistory()
        {
            return Ok(Transaction.CreateTransactions());
        }

        [Route("transfer")]
        [TwoFactorAuthorize]
        public IHttpActionResult PostTransfer(TransferModeyModel transferModeyModel)
        {
            return Ok();
        }
    }

    #region Helpers

    public class Transaction
    {
        public int ID { get; set; }
        public string CustomerName { get; set; }
        public string Amount { get; set; }
        public DateTime ActionDate { get; set; }


        public static List<Transaction> CreateTransactions()
        {
            List<Transaction> TransactionList = new List<Transaction> 
            {
                new Transaction {ID = 10248, CustomerName = "Taiseer Joudeh", Amount = "$1,545.00", ActionDate = DateTime.UtcNow.AddDays(-5) },
                new Transaction {ID = 10249, CustomerName = "Ahmad Hasan", Amount = "$2,200.00", ActionDate = DateTime.UtcNow.AddDays(-6)},
                new Transaction {ID = 10250,CustomerName = "Tamer Yaser", Amount = "$300.00", ActionDate = DateTime.UtcNow.AddDays(-7) },
                new Transaction {ID = 10251,CustomerName = "Lina Majed", Amount = "$3,100.00", ActionDate = DateTime.UtcNow.AddDays(-8)},
                new Transaction {ID = 10252,CustomerName = "Yasmeen Rami", Amount = "$1,100.00", ActionDate = DateTime.UtcNow.AddDays(-9)}
            };

            return TransactionList;
        }
    }

    public class TransferModeyModel
    {
        public string FromEmail { get; set; }
        public string ToEmail { get; set; }
        public double Amount { get; set; }
    }

    #endregion
}

Notice that the “Authorize” attribute is set on the controller level for both actions, which means that both actions need the bearer token to process the request, but on the action method “PostTransfer” you will notice that there is new custom authorize filter attribute named “TwoFactorAuthorizeAttribute” setting on top of this action method, this custom authorize attribute is responsible for enabling Two Factor authentication on any sensitive controller, action method, or HTTP verb in future. All we need to do is just use this custom attribute as an attribute on the endpoint we want to elevate the security level on and require a second factor authentication to process the request.

Step 10: Implement the “TwoFactorAuthorizeAttribute”

Before starting to implement the “TwoFactorAuthorizeAttribute” we need to add simple helper class which will be responsible to inspect request headers looking for the time sensitive passcode sent by the client application in a custom header, so to implement this add a new folder named “Helpers” and inside it add a new file named “OtpHelper” and paste the code below:

public static class OtpHelper
    {
        private const string OTP_HEADER = "X-OTP";

        public static bool HasValidTotp(this HttpRequestMessage request, string key)
        {
            if (request.Headers.Contains(OTP_HEADER))
            {
                string otp = request.Headers.GetValues(OTP_HEADER).First();
                
                // We need to check the passcode against the past, current, and future passcodes
               
                if (!string.IsNullOrWhiteSpace(otp))
                {
                    if (TimeSensitivePassCode.GetListOfOTPs(key).Any(t => t.Equals(otp)))
                    {
                        return true;
                    }
                }

            }
            return false;
        }
    }

So basically this class is looking for a custom header named “X-OTP” in the HTTP request headers, if this header was found we’ll send the value of it (time sensitive passcode) along with Preshared key for this authenticated user to the method “GetListOfOTPs” which we defined in step 7.

If this time sensitive passcode exists in the list of pass codes (past, current, and future passcodes) then this means that this passcode is valid and authentic, otherwise the passcode is invalid or the user didn’t include it in the request.

Now to implement the custom “TwoFactorAuthorizeAttribute” we need to add a new folder named “Filters” and inside it add a new class named “TwoFactorAuthorizeAttribute” then paste the code below:

public class TwoFactorAuthorizeAttribute : AuthorizationFilterAttribute
    {
        public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;

            var preSharedKey = principal.FindFirst("PSK").Value;
            bool hasValidTotp = OtpHelper.HasValidTotp(actionContext.Request, preSharedKey);

            if (hasValidTotp)
            {
                return Task.FromResult<object>(null);
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new CustomError() { Code = 100, Message = "One Time Password is Invalid" });
                return Task.FromResult<object>(null);
            }
        }
    }

    public class CustomError
    {
        public int Code { get; set; }
        public string Message { get; set; }
    }

What we’ve implemented in this customer authorization filer is the following:

  • This custom Authorize attribute inherits from “AuthorizationFilterAttribute” and we are overriding the “OnAuthorizationAsync” method.
  • We can be 100% sure that the code execution flow will not reach this authorization filter attribute if the user is not authenticated by the OAuth 2.0 bearer token sent, this custom authorize attribute run later in the pipeline after the “Authorize” attribute.
  • Inside the “OnAuthorizationAsync” method we are looking for the claims for the authenticated user, this claim will contain custom claim of type “PSK” which contains the value of the Preshared key for this authenticated user (Didn’t implement this yet, you will see how we set the claim in the next step).
  • Then we will call the helper method named “OtpHelper.HasValidTotp” by passing the HTTP request which contains the time sensitive pass code in a custom header along with the Preshared key. If this method returns true then we will consider this request a valid one and that has fulfilled the Two Factor authentication requirements.
  • If the request doesn’t contain the valid time sensitive passcode then we will return HTTP status code 401 along with a message and an arbitrary integer code used in the UI.

 Step 11: Implement the “SimpleAuthorizationServerProvider” class

Add a new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
            return Task.FromResult<object>(null);
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var  allowedOrigin = "*";
            ApplicationUser appUser = null;

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            using (AuthRepository _repo = new AuthRepository())
            {
                 appUser = await _repo.FindUser(context.UserName, context.Password);

                if (appUser == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "User"));
            identity.AddClaim(new Claim("PSK", appUser.PSK));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
        }

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {

            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }
    }

It is worth mentioning here that in the second method “GrantResourceOwnerCredentials” which is responsible for validating the username and password sent to the authorization server token endpoint, and after fetching the user from the database, we are adding a custom claim named “PSK”, the value for this claim contains the Preshared key for this authenticated user. This claim will be included in the signed OAuth 2.0 bearer token, that’s why we can directly get the PSK value in step 10.

 Step 12: Testing the Back-end API

First step to test the API is to register a new user so open your favorite REST client application in order to issue an HTTP request to register the user, so issue an HTTP POST request to the endpoint https://ngtfaapi.azurewebsites.net/api/account/register as the image below:

Register User

If the request processed successfully you will receive 200 status along with the Preshared Key, so open Google Authenticator app and enter this key manually.

Now we need to obtain OAuth 2.0 bearer access token to allow us to request the protected end points, this represent the first factor authentication because the user will provide his username and password, so we need to issue HTTP POST request to the endpoint http://ngtfaapi.azurewebsites.net/token as the image below:

Request Access Token

Now after we have a valid OAuth 2.0 access token, we need to try to send an HTTP POST request to the protected elevated security endpoint which requires second factor authentication, we’ll issue the request to the endpoint https://ngtfaapi.azurewebsites.net/api/transactions/transfer asshown in the image below, but we’ll not set the value for the custom header (X-OTP) so definitely the API will response with 401 unauthorized access

Failed TFA Request

Now in order to make this request authentic we need to open Google Authenticator and get the passcode from there and send it in the (X-OTP) custom header, so the authentic request will be as shown in the image below:

Authentic TFA Request

The live AngularJS demo application is hosted on Azure, the source code for this tutorial on GitHub.

That’s it for now folks!

I hope this step by step post will help you enable Two Factor Authentication into ASP.NET Web API RESTful services for selective sensitive endpoints, if you have any question please drop me a comment.

Follow me on Twitter @tjoudeh

References

The post Two Factor Authentication in ASP.NET Web API & AngularJS using Google Authenticator appeared first on Bit of Technology.


Dominick Baier: IdentityServer v3 Beta 2-1

We just did a minor update to Beta 2.

Besides some smaller changes and bug fixes we now support redirecting back to a client after logout (very requested feature). I will write a blog post soon describing how it works.


Filed under: IdentityServer, OAuth, OpenID Connect, WebAPI


Dominick Baier: Getting started with IdentityServer v3

Last night I started working on a getting started tutorial for IdentityServer v3 – while writing it, it became clear, that a single walkthrough will definitely not be enough to show the various options you have – anyways I started with the canonical “authentication for MVC scenario”, and it is work in progress.

Watch this space:

https://github.com/thinktecture/Thinktecture.IdentityServer.v3/wiki


Filed under: ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: OpenID Connect Hybrid Flow and IdentityServer v3

One of the features we added in Beta 2 is support for hybrid flow (see spec).  What is hybrid flow – and why do I care?

Well – in a nutshell – OpenID Connect originally extended the two basic OAuth2 flows (or grants) called authorization code and implicit. Implicit allows requesting tokens without explicit client authentication (hence the name), but uses the redirect URI instead to verify client identity. Because of that, requesting long lived tokens like a refresh token is not allowed in that flow.

Authorization code flow on the other hand only returns a so called authorization code via the unauthenticated front channel, and requires client authentication using client id and secret (or some other mechanism) to retrieve the actual tokens (including a refresh token) via the back channel. This mechanism was originally designed for server-based applications only, since storing client secrets on a client device is questionable without the right security mechanisms in place.

Hybrid flow (as the name indicates) is a combination of the above two. It allows to request a combination of identity token, access token and code via the front channel using either a fragment encoded redirect (native and JS based clients) or a form post (server-based web applications). This enables e.g. scenarios where your client app can make immediate use of an identity token to get access to the user’s identity but also retrieve an authorization code that that can be used (e.g. by a back end service) to request a refresh token and thus gaining long lived access to resources.

Lastly, hybrid flow is the only flow supported by the Microsoft OpenID Connect authentication middleware (in combination with a form post response mode), and before we added support for hybrid flow to IdentityServer, interop was a bit complicated (see here).

Our samples repo has two clients using hybrid flow – native and web. Let’s have a look at the middleware based one.

You are using hybrid flow whenever you have a response type of code combined with some other response type, e.g. id_token or token (or both).

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions

    {

        ClientId = “katanaclient”,

        Authority = Constants.BaseAddress,

        RedirectUri = Constants.RedirectUri,

        PostLogoutRedirectUri = Constants.PostLogoutUri,

        ResponseType = “code id_token token”,

        Scope = “openid email profile read write offline_access”,

 

        SignInAsAuthenticationType = “Cookies”

    };

 

The scopes are a combination of identity scopes allowing us to retrieve user identity (email and profile), resource scopes for api access (read and write) and a request for a refresh token (offline_access).

After authentication (and consent), the middleware will validate the response and notify you when it has retrieved the authorization code from the callback form post. You then typically have a number of responsibilities, e.g.

  • Contact the userinfo endpoint to retrieve the claims about the user
  • Transform the claims to whatever format your application expects
  • Store the access token for later use (along with information about its lifetime)
  • Store the refresh token so you can refresh expired access tokens (if long lived access is needed)
  • Store the id_token if you need features at the OpenID Connect provider that requires id token hints (e.g. redirects after logging out)

In our sample, I first strip all the protocol related claims from the identity token:

// filter "protocol" claims
var claims = new List<Claim>(from c in n.AuthenticationTicket.Identity.Claims
                                where c.Type != "iss" &&
                                      c.Type != "aud" &&
                                      c.Type != "nbf" &&
                                      c.Type != "exp" &&
                                      c.Type != "iat" &&
                                      c.Type != "nonce" &&
                                      c.Type != "c_hash" &&
                                      c.Type != "at_hash"
                                select c);

 

…then get the user claims from the user info endpoint

// get userinfo data
var userInfoClient = new UserInfoClient(
    new Uri(Constants.UserInfoEndpoint),
    n.ProtocolMessage.AccessToken);
 
var userInfo = await userInfoClient.GetAsync();
userInfo.Claims.ToList().ForEach(ui => claims.Add(new Claim(ui.Item1, ui.Item2)));

 

…and retrieve a refresh token (and a fresh access token)

// get access and refresh token
var tokenClient = new OAuth2Client(
    new Uri(Constants.TokenEndpoint),
    "katanaclient",
    "secret");
 
var response = await tokenClient.RequestAuthorizationCodeAsync(
    n.Code, n.RedirectUri);

 

Then I combine all the claims together and store them in the authentication cookie:

claims.Add(new Claim("access_token", response.AccessToken));
claims.Add(new Claim("expires_at", 
    DateTime.Now.AddSeconds(response.ExpiresIn).ToLocalTime().ToString()));
claims.Add(new Claim("refresh_token", response.RefreshToken));
claims.Add(new Claim("id_token", n.ProtocolMessage.IdToken));
 
n.AuthenticationTicket = new AuthenticationTicket(
    new ClaimsIdentity(claims.Distinct(new ClaimComparer()), 
        n.AuthenticationTicket.Identity.AuthenticationType), 
        n.AuthenticationTicket.Properties);

 

You might not need all of the above steps, but this is how it generally works. HTH.


Filed under: IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: Identity & Access Control at NDC London 2014

The NDC Agenda is out now – and Brock and me will do a number of identity & access control related sessions.

Brock will talk about identity management in ASP.NET – which is a huge topic – so he split up his talk into two sessions. I will cover OpenID Connect and OAuth2 – and especially the combination of the two protocols. Looking forward to that!

In addition we will do a 2-day workshop on monday/tuesday titled: “Identity & Access Control for modern Web Applications & APIs” – this will be deep dive in all the things you need to know to implement authentication and authorization into modern distributed applications. See the agenda here.

Early bird ends on 15th October – would be cool to meet you there and talk about security!


Filed under: .NET Security, ASP.NET, IdentityModel, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Dominick Baier: IdentityServer v3 – Beta 2

We just pushed IdentityServer v3 beta 2 to github and nuget.

This time it’s been 161 commits and we added a lot of small things – and a couple of bigger things, e.g.:

  • Update to Katana v3 and JWT handler v4
  • Configurable claims for both identity and resource scopes
  • Added support for acr_values and tenant login hints
  • Improved support for custom grant types
  • Added a RequireSsl switch (thus removing the need for the public host name setting)
  • Reworked some internals like the user service, token service, userinfo endpoint, sign in message and validation pipeline
  • Added support for hybrid flow and thus improved compatibility with the Microsoft Katana OpenID Connect middleware
  • Added identity token validation endpoint for clients that don’t have access to the necessary crypto libraries
  • More control over CSP and cookies

Docs will be updated in the next days.

As always – thank you very much for feedback, bug reports etc… we are getting closer to RTW!


Filed under: ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Filip Woj: Route matching and overriding 404 in ASP.NET Web API

In ASP.NET Web API, if the incoming does not match any route, the framework is simply hard wired to return 404 to the client (or possibly pass through to the next configured middleware, in case of an OWIN hosted Web … Continue reading

The post Route matching and overriding 404 in ASP.NET Web API appeared first on StrathWeb.


Christian Weyer: Installing Running ASP.NET vNext (Alpha 3) on Ubuntu Linux with Mono 3.8for real

Yesterday I thought I would try and prove Microsoft’s promise that the new and overall cool ASP.NET vNext would run on many platforms, including Windows, MacOS X, and Linux.

My target platform for this experiment was Linux. First thing to do in this case is check out of of the myriads of Linux distros. After a bit of investigating I chose the Ubuntu-based Xubuntu. Very slick!

After installing Xubunutu (it took only a few minutes, literally) in a Parallels VM on my MacBook Pro, I went ahead to get Mono running. Turns out the the most reliable way to get recent versions of Mono running on stable Linux distros these days is to suck down the source code and compile it.
So here we go with some simple steps (may take a couple of minutes to get through, though):

sudo apt-get install build-essential
wget http://download.mono-project.com/sources/mono/mono-3.8.0.tar.bz2
tar -xvf mono-3.8.0.tar.bz2
cd mono-3.8.0/
./configure --prefix=/usr/local
make
sudo make install


This gives us the Mono 3.8.0 CLI:

mono_cli


According to the ASP.NET vNext Home repo on GitHub this should be all we need to get started with the samples. NOT. When we build the source of the samples we get a network-related exception showing up.

The issue is the certificates used for the package sources. The .NET Framework on Windows uses the Windows Certificates store to check whether to accept an SSL certificate from a remote site. In Mono, there is no Windows Certificate store, it has its own store. By default, it is empty and we need to manage the entries ourselves.

CERTMGR=/usr/local/bin/certmgr
sudo $CERTMGR -ssl -m https://go.microsoft.com
sudo $CERTMGR -ssl -m https://nugetgallery.blob.core.windows.net
sudo $CERTMGR -ssl -m https://nuget.org
sudo $CERTMGR -ssl -m https://www.myget.org/F/aspnetvnext/

mozroots --import --sync

After these steps we should be able to build the samples from the ASP.NET vNext Home repo successfully, e.g. the HelloMvc sample.

Running kpm restore looks promising, at least:

kpm_restore

When we then try to run the sample with k kestrel (Kestrel is the current dev web server in vNext) we get a wonderfully familiar error:

Object reference not set to an instance of an object.

Hooray!!! Sad smile

After some Googling I found out that the underlying libuv (yes, that same libuv used in node.js) seems to be the problem here. A quick chat with the ASP.NET vNext team reveals it seems like this will be fixed in the future, but there are some more important things to get done by now.

Anyway, I got it finally to work by replacing libuv as suggested here:

ln -sf /usr/lib/libuv.so.11 native/darwin/universal/libuv.dylib

 

When I now run k kestrel again everything is fine:

k_kestrel_running

By default, Kestrel runs on port 5004 – thus opening our browser of choice with http://localhost:5004 gives us the desired result:

running

Mission accomplished.
Thanks for listening.


Darrel Miller: RESTFest 2014

Last week was RESTfest week.  RESTfest is an unusual little conference that happens in Greenville, South Carolina every September.  This is the fifth year it has run and this is my fourth time attending, and I learn a ton every time.

RESTFest

What makes RESTFest unique is its “everyone speaks” policy.  Although there is a keynote, a whole hack day and a number of regular length talks, the bulk of the conference time is made up of 5 minute lightning talks presented by attendees.

This is not just a conference full of people who have spent years drinking the REST coolaid.  There is always a wide range of experience levels and people with many different technical backgrounds.  This combination makes for some great conversations, and there is plenty of time for them with the social activities that are scheduled during the event.

WP_20140926_001This years keynote was presented by Sean Cribbs.  RESTFest keynotes have a tendency to challenge the audience intellectually and this year’s crash course in the functional programming theory that is the underpinning of WebMachine was no different.

The hack day was a challenge to create a hypermedia client and/or server based on a simple specification.  The interesting outcome was the wide variety of solutions presented.  We had people using Erlang, .net, Java, AngularJS with HAL, C+J, Siren, Atom and HTML hypermedia types being used.  It’s also important to realize that a large part of the value of hack day is not the code writing, but the opportunity to see how others are writing code and talking with them about it.  It’s all just conversation fodder.

Did I mention there was moonshine tasting going on?

WP_20140925_002

And the food is awesome,

WP_20140927_001

There is one more thing that makes RESTfest fairly unique amongst small “unconference” style events and that is that we have had a tradition of recording the sessions.  The first couple of years have fairly poor quality videos because I used an ipad to stream the talks using uStream.  In the third year, Twilio stepped up to the plate and paid for professional videos to be done.  Since then, every year, a sponsor has allowed us to create a fabulous catalog of talks.  These are all available on the Vimeo RESTfest channel.

If you want to learn more about APIs, HTTP, Hypermedia, or REST in general, you really should make an effort to join us in 2015.


Dominick Baier: 401 vs 403

For years, there’s been an ongoing discussion which HTTP status code to use for “not authorized” scenario – and the original HTTP 1.1 specification wasn’t exactly crystal clear about the distinction between 401 (unauthorized) and 403 (forbidden).

But there is definitely the need to distinguish between the situation where no or invalid credentials were supplied with a request and the situation where a valid credential was supplied, but the “entity” belonging to that credential is not authorized for the operation it is trying to do.

Here are some examples:

  • In good old ASP.NET FormsAuth (well this also applies to the brand new cookie middleware in Katana) – a 401 is turned into a 302 to the login page. That’s fine for anonymous requests – but when a user is already authenticated, a failed authorization (e.g. using [Authorize(Role=”foo”)]) will result in showing the login page again – not very intuitive. You rather want do deal with that error or or show an error page.
  • In Web APIs and token based authentication your client need to be able to distinguish if the token is e.g. expired or if it is missing the necessary scopes. The “Bearer Token Usage” spec (http://tools.ietf.org/html/rfc6750) is pretty clear about this. Expired or malformed tokens should return a 401 – missing scopes should result in a 403.

You might have heard that the HTTP 1.1 spec has been re-written recently. It is now clearer on the status codes as well (you know it is getting serious when you see a Courier font, right?):

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.

A server that receives valid credentials that are not adequate to gain access ought to respond with the 403 (Forbidden) status code.

Unfortunately, the ASP.NET MVC/Web API [Authorize] attribute doesn’t behave that way – it always emits 401. The logic would be simple for failed authorization: “if user is anonymous – emit 401, if not – emit 403” (we now emit 403s for our scope authorization helpers – here and here).

Maybe we can fix that in vNext.


Filed under: .NET Security, ASP.NET, Katana, OAuth, OWIN, WebAPI


Ali Kheyrollahi: Performance Counters for your HttpClient

Level [T2]

Pure HTTP APIs (aka REST APIs) are very popular at the moment. If you are building/maintaining one, you have probably learnt (perhaps the hard way) that having a monitoring on your API is one of your top cross-cutting concerns. This monitoring involves different aspects of the API, one of which is the performance.

There has been many approaches to solving cross-cutting concerns on APIs. Proxying has been a popular one and there has been proliferation of proxy type services such as Mashery or Apigee which basically sit in front of your API and provide an abstraction which can solve your security and access control, monetizing or performance monitoring.

This is a popular approach but comes with its headaches. One of these problems is that if you already have a security mechanism in place, it can clash with the one provided by the service. Also the geographic distribution of these services, although are getting better, is not as good as the one provided by many cloud vendors. This can mean that your traffic could be bouncing across the Atlantic ocean a couple of times before getting to your end users - and this is bad, really really bad. On the other hand, these will not tell you what is happening inside your application which you have to solve differently using classic monitoring approaches. So in a sense, I would say you might as well just byte! the bullet and just implement it yourself.

PerfIt was a library I built a couple of years ago to provide performance counters for ASP.NET Web API. Creating and managing performance counters for windows is not a rocket science but is clumsy and once you do it over and over and for every service, this is just a bit too much overhead. So this was designed to make it really simple for you... well, actually for myself :) I have been using PerfIt over the last two years - in production - and it serves the purpose.

Now, it is all well and good to know what is the performance characteristics of your API. But this gets really more complicated when you have taken a dependency on other APIs and degradation of your API is the result of performance issues in your dependent APIs.




This is really a blame game: considering the fact that each MicroServie is managed by a single team and in an ideal DevOps world, the developers must support their services and you would love to blame another team rather than yourself especially if this is truly the direct result of performance degradation in a dependent service.

One solution is have access to performance metrics of the dependent APIs but really this might not be possible and kinda goes against the DevOps model of operations. On the other hand, what if this is due to an issue in an intermediary - such as a Proxy?

The real solution is to benchmark and monitor the calls you are making out of your API. And I have implemented a new DelegatingHandler to do that measurement for you!


PerfIt! for HttpClient

So HttpClient is the de-facto class for accessing HTTP APIs. If you are using something else then either you have a really really good reason to do so or you are just doing it wrong.

PerfIt for client provides 4 standard counters out of the box:

  • Total # of operations
  • Average time taken (in seconds)
  • Time taken for the last operation (in ms)
  • # of operations per second

These are the 4 counters that you would normally need. If you need another, just get in touch with me but remember these counters must be business-independent.

First step is to install PerfIt using NuGet:
PM> Install-Package PerfIt
And then you just need to install the counters for your application. This can be done by running this simple code (categoryName is the performance counter grouping):
PerfItRuntime.InstallStandardCounters("<categoryName>");
Or by using an installer class as explained on the GitHub page and then running InstallUtil.exe.

Now, just add PerfitClientDelegatingHandler to your HttpClient and make some requests against a couple of websites:
using System;
using System.Net.Http;
using PerfIt;
using RandomGen;

namespace PerfitClientTest
{
class Program
{
static void Main(string[] args)
{
var httpClient = new HttpClient(new PerfitClientDelegatingHandler("ClientTest")
{
InnerHandler = new HttpClientHandler()
});

var randomSites = Gen.Random.Items(new[]
{
"http://google.com",
"http://yahoo.com",
"http://github.com"
});
for (int i = 0; i < 100; i++)
{
var httpResponseMessage = httpClient.GetAsync(randomSites()).Result;
Console.Write("\r" + i);
}

}
}
}
And now you should be seeing this (we have chosen "ClientTest" for the category name):

So as you can see, instance names are the host names of the APIs and this should provide you with enough information for you to monitor your dependencies. Any deeper information than this and then you really need tracing rather than monitoring - which is a completely different thing...



So as you can see, it is extremely easy to set this up and run it. I might expose the part of the code that defines the instance name which will probably be coming in the next versions.

Please use the GitHub page to ask questions or provide feedbacks.



Dominick Baier: IdentityServer Beta 1-2

Yesterday we pushed another interim release of IdentityServer to nuget.  You can see all commits here if you are interested.

Besides many smaller changes and bug fixes – the main new feature is that you can now configure which claims go into identity and access tokens. This allows sending e.g. a ‘role’ claim to a resource.

Before that change, this always required extending the claims provider. Check the wiki for updated docs.

Internally, everything is based now on Katana and the JWT handler v4 – which allowed to finally fix the data types of claims like ‘iat’ or ‘auth_time’ to numbers (before that the JWT handler only allowed strings). This improvers interop with other OIDC systems. Katana v3 is also a pre-req for supporting WS-Federation and OIDC based upstream IdPs, which is a feature that we will soon start working on.

We also moved all active development to the dev branch and periodically publish dev nugets to myget. See here.

As always, and feedback is appreciated. Thanks for the support so far!


Filed under: .NET Security, ASP.NET, IdentityServer, Katana, OAuth, OpenID Connect, OWIN, WebAPI


Darrel Miller: Vermont Code Camp

This past weekend I had the opportunity to attend and speak at Vermont Code Camp.  Apart from being hosted at the beautiful University of Vermont, it was an event packed with excellent speakers.

I presented my talk on “Crafting Evolvable API Responses”, which itself managed to evolve considerably since doing it at New York Code camp the weekend before.  The slides are available here on slideshare:

It was also great to see such a great showing of women speakers.

vtcodecamp

If you get the chance next year to attend, this is one event that I would definitely recommend.


Taiseer Joudeh: Decouple OWIN Authorization Server from Resource Server

Recently I’ve received lot of comments and emails asking how we can decouple the OWIN Authorization Server we’ve built in the previous posts from the resources we are protecting. If you are following the posts mentioned below you will notice that we’ve only one software component (API) which plays both roles: Authorization Server and Resource Server.

There is nothing wrong with the the current implementation because OAuth 2.0 specifications never forces the separation between the Authorization Server and the Resource Server, but in many cases and especially if you have huge resources and huge number of endpoints you want to secure; then it is better from architecture stand point to decouple the servers. So you will end up having a stand alone Authorization Server, and another stand alone Resource Server which contains all protected resources, as well this Resource Server will understand only the access tokens issued from the Authorization Server.

You can check the source code on Github.


OAuth 2.0 Roles: Authorization Server, Resource Server, Client, and Resource Owner

Before we jump into implementation and how we can decouple the servers I would like to emphasis on OAuth 2.0 roles defined in the specifications; so we’ll have better understanding of the responsibility of each role, by looking at the image below you will notice that there are 4 roles involved:

OAuth 2.0 Roles

Resource Owner:

The entity or person (user) that owns the protected Resource.

Resource Server:

The server which hosts the protected resources, this server should be able to accept the access tokens issued by the Authorization Server and respond with the protected resource if the the access token is valid.

Client Applications:

The application or the (software) requesting access to the protected resources on the Resource Server, this client (on some OAuth flows) can request access token on behalf of the Resource Owner.

Authorization Server:

The server which is responsible for managing authorizations and issuing access tokens to the clients after validating the Resource Owner identity.

Note: In our architecture we can have single Authorization Server which is responsible to issue access token which can be consumed by multiple Resource Servers.

Decoupling OAuth 2.0 OWIN Authorization Server from Resource Server

In the previous posts we’ve built the Authorization Server and the Resource Server using a single software component (API), this API can be accessed on (http://ngauthenticationAPI.azurewebsites.net), in this demo I will guide you on how to create new standalone Resource API and host it on different machine other than the Authorization Server machine, then configure the Resource API to accept only access tokens issued from our Authorization Server. This new Resource Server is hosted on Azure can be accessed on (http://ngauthenticationResourcesAPI.azurewebsites.net).

Note: As you noticed from the previous posts we’ve built a protected resource (OrdersController) which can be accessed by issuing HTTP GET to the end point(http://ngauthenticationAPI.azurewebsites.net/api/orders), this end point is considered as a resource and should be moved to the Resource Server we’ll build now, but for the sake of keeping all the posts on this series functioning correctly; I’ll keep this end point in our Authorization Server, so please consider the API we’ve built previously as our standalone Authorization Server even it has a protected resource in it.

Steps to build the Resource Server

In the steps below, we’ll build another Web API which will contain our protected resources, for the sake of keeping it simple, I’ll add only one secured end point named “ProtectedController”, any authorized request to this end point should contain valid bearer token issued from our Authorization Server, so let’s start implementing this:

Step 1: Creating the Resource Web API Project

We need to add new ASP.NET Web application named “AngularJSAuthentication.ResourceServer” to our existing solution named “AngularJSAuthentication”, the selected template for the new project will be “Empty” template with no core dependencies, check the image below:

Resourse Server New Project

Step 2: Install the needed NuGet Packages

This project is empty so we need to install the NuGet packages needed to setup our OWIN Resource Server, configure ASP.NET Web API to be hosted within an OWIN server, and configure it to only uses OAuth 2.0 bearer tokens as authorization middle ware; so open NuGet Package Manager Console and install the below packages:

Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Cors -Version 3.0.0
Install-Package Microsoft.Owin.Security.OAuth -Version 2.1.0

The usage for each package has been covered on the previews posts, feel free to check this post to know the rational of using each package is used for.

Important note: In the initial post I was using package “Microsoft.Owin.Security.OAuth” version “3.0.0″ which differs from the version used in the Authorization Server version “2.1.0″, there was a bug in my solution when I was using 2 different versions, basically the bug happens when we send an expired token to the Resource Server, the result for this that Resource Server accepts this token even if it is expired. I’ve noticed that the properties for the Authentication ticket are null and there is no expiry date. To fix this issue we need to unify the assembly version “Microsoft.Owin.Security.OAuth” between the Authorization Server and the Resource Server, I believe there is breaking changes between those 2 versions that’s why ticket properties are not de-crypted and de-serialized correctly.  Thanks for Ashish Verma for notifying me about this.

Step 3: Add OWIN “Startup” Class

Now we want to add new class named “Startup”. It will contain the code below:

[assembly: OwinStartup(typeof(AngularJSAuthentication.ResourceServer.Startup))]
namespace AngularJSAuthentication.ResourceServer
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            ConfigureOAuth(app);

            WebApiConfig.Register(config);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(config);
            
        }

        private void ConfigureOAuth(IAppBuilder app)
        {
            //Token Consumption
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
            });
        }
    }
}

As we’ve covered in previous posts, this class will be fired once our Resource Server starts, as you noticed I’ve enabled CORS so this resource server can accept XHR requests coming from any origin.

What worth noting here is the implementation for method “ConfigureOAuth”, inside this method we are configuring the Resource Server to accept (consume only) tokens with bearer scheme, if you forget this one; then your Resource Server won’t understand the bearer tokens sent to it.

Step 3: Add “WebApiConfig” Class

As usual we need to add the WebApiConfig class under folder “App_Start” which contains the code below:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }

This class is responsible to enable routing attributes on our controller.

Step 4: Add new protected (secured) controller

Now we want to add a controller which will serve as our protected resource, this controller will return list of claims for the authorized user, those claims for sure are encoded within the access token we’ve obtained from the Authorization Server. So add new controller named “ProtectedController” under “Controllers” folder and paste the code below:

[Authorize]
    [RoutePrefix("api/protected")]
    public class ProtectedController : ApiController
    {
        [Route("")]
        public IEnumerable<object> Get()
        {
            var identity = User.Identity as ClaimsIdentity;
           
            return identity.Claims.Select(c => new
            {
                Type = c.Type,
                Value = c.Value
            });
        }
    }

Notice how we attribute the controller with [Authorize] attribute which will protect this resource and only will allow HTTP GET requests containing a valid bearer access token sent in the authorization header to pass, in more details when the request is received the OAuth bearer authentication middle ware will perform the following:

  1. Extracting the access token which is sent in the “Authorization header” with the “Bearer” scheme.
  2. Extracting the authentication ticket from access token, this ticket will contain claims identity and any additional authentication properties.
  3. Checking the validity period of the authentication ticket.

Step 5: Hosting the Authorization Server and Resource Server on different machines

Until this step and if you are developing locally on your dev machine, if you tried to obtain an access token from your Authorization Server i.e. (http://AuthServer/token) and then send this access token to the secured end point in our Resource Server i.e. (http://ResServer/api/protected) the result for this request will pass and you will have access to the protected resource, how is this happening?

One your dev machine once you request an access token from your Authorization Server; the OAuth middleware will use the default data protection provider in your Authorization Server, so it will use the “validationKey” value in machineKey node stored in machine.config file to issue the access token and protect it. The same case applies when you send the access token to your Resource Server, it will use the same machineKey to decrypt the access token and extract the authentication ticket from it.

The same applies if you are planing on your production environment to host your Authorization Server and your Resource Server on the same machine.

But in our case I’m hosting my Authorization Server on Azure website using West-US region, and my Resource Server is hosted on Azure websites on East-US region so both are totally on different machines and they share different machine.config files. For sure I can’t change anything on machine.config file because it is used by different sites on the Azure VMs I’m hosting my APIs on it.

So to solve this case we need to override the machineKey node for both APIs (Authorization Server and Resource Server) and share the same machineKey between both web.config files.

To do so we need to generate a new machineKey using this online tool, the result after using the tool will be as the below: As advised by Barry Dorrans it is not recommend to use an online tool to generate your machineKey because you do not know if this online tool will store the value for your machineKey in some secret database, it is better to generate the machineKey by your self.

To do so I’ll follow the steps mentioned in article KB 2915218, Appendix A which uses Power Shell commands to generate machineKey, so after you open Power Shell and run the right command as the image below you will receive new machineKey
PowerShell MachineKey

<machineKey validationKey="A970D0E3C36AA17C43C5DB225C778B3392BAED4D7089C6AAF76E3D4243E64FD797BD17611868E85D2E4E1C8B6F1FB684B0C8DBA0C39E20284B7FCA73E0927B20" decryptionKey="88274072DD5AC1FB6CED8281B34CDC6E79DD7223243A527D46C09CF6CA58DB68" validation="SHA1" decryption="AES" />

Note: Do not use those for production and generate a new machineKey for your Servers using Power Shell.

After you generate it open the web.config file for both the Authorization Server (AngularJSAuthentication.API project) and for the Resource Server (AngularJSAuthentication.ResourceServer) and paste the machineKey node inside the <system.web> node as the below:

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <machineKey validationKey="VALUE GOES HERE" 
                decryptionKey="VALUE GOES HERE" 
                validation="SHA1" 
                decryption="AES"/>
  </system.web>

By doing this we’ve unified the machineKey for both Authorization Server and Resource Server (Only this API in case of Azure shared hosting or any other shared host) and we are ready now to test our implementation.

Step 6: Testing the Authorization Server and Resource Server

Now we need to obtain an access token from our Authorization Server as we did before in the previous posts, so we can issue HTTP POST to the end point (http://ngauthenticationapi.azurewebsites.net/token) including the resource owner username and password as the image below:

Obtain Access Token

If the request succeeded we’ll receive an access token, then we’ll use this access token to send HTTP GET request to our new Resource Server using the protected end point (http://ngauthenticationresourcesapi.azurewebsites.net/api/protected), for sure we need to send the access token in the Authorization header using bearer scheme, the request will be as the image below:

Consume Access Token

As you notice we’re now able to access the protected resource in our new Resource Server and the claims for this identity which obtained from the Authorization Server are extracted.

That’s it for now folks, hopefully this short walk through helped in understanding how we can decouple the Authorization Server from the Resource Server.

If you have any comment or question please drop me a comment

You can use the following link to check the demo application.

You can use the following link to test the Authorization Server (http://ngauthenticationAPI.azurewebsites.net),

You can use the following link to test the Resource Server (http://ngauthenticationResourcesAPI.azurewebsites.net) 

You can check the source code on Github.

Follow me on Twitter @tjoudeh

References

The post Decouple OWIN Authorization Server from Resource Server appeared first on Bit of Technology.


Glenn Block: Our new book and my personal journey toward REST and Hypermedia

It’s hard to believe, but it has been 6 months since our new book, “Designing Evolvable Web APIs with ASP.NET” shipped! So far the feedback that we’ve received has been really positive and we’re excited to see the momentum.

book

In the first part of the book we focus on educating about the fundamentals of the web architecture and HTTP, and APIs. Next we focus on the designing of a hypermedia API, and a TDD/BDD driven implementation of a CollectionJson API using ASP.NET Web API. We also give you several coding patterns that you can use to get started building hypermedia APIs.

In the second part of the book, we focus on ASP.NET Web API itself and the underlying architecture. We do this in the context of the first part, with the explicit goal of helping you further toward building out an evolvable API. We delve deeply into the nuts and bolts of Web API including hosting, routing and model binding. We cover comprehensively how to secure your API, and the security internals. And we cover other topics like TDD and using Inversion of Control.

You can buy it online now here. We also have a Github repo with all the code, which includes a working hypermedia API.

The people that made this book a reality.

This book has been a collaborative effort with four other amazing folks that I’ve had the privilege to work with. It combines the knowledge of the Web API team itself as well as key advisors who were with us every step of the way as we built it. It was a collaborative effort across 4 time zones and countries:

  • Howard Dierking, my co-conspirator on the Web API team. An amazing individual who is helping educate the world on REST and hypermedia through his Pluralsight work.
  • Darrel Miller, a long time proponent of REST and hypermedia in the .NET world before many of us at Microsoft had a clue of what that means. Darrel has been building real hypermedia systems for a long time. Darrel was one of our first handfuls of advisors on Web API.
  • Pedro Felix, an expert on Web API security and the ASP.NET Web API architecture. His comprehensive contribution in the book on the security aspects of Web API is unparalleled in the .NET world.
  • Pablo Cibraro, former CTO of Tellago and a consultant who has implemented many API solutions. Pablo is an expert in Agile and TDD, and he wrote some deep chapters testability and IOC.

We also had a fantastic set of reviewers and advisors.

Why write this book?

This book is part of a very personal journey, a  journey that started several years ago when I joined the WCF team at Microsoft. At that time I had the pop culture understanding of REST, that is a lightweight API exposed over HTTP that doesn’t use SOAP. I joined the team to help build a better experience in the platform for these types of APIs. Little did I know the journey that awaited me, as I would delve deeper and deeper into the REST community.

It was a journey of learning.  I was fortunate to have wonderful teachers who had already been treading the path, chief of which (ordered last name first) were: Jan Algermissen, Mike Amundsen Alan Dean, Mike Kelly, Sebastien Lambla, Darrel Miller, Henrik Nielsen, Ian Robinson, Aaron Skonnard, and Jim Webber. I am deeply indebted for their help. The is book was built really on the shoulders of these giants!

During that period, I learned about HTTP and REST, that REST is much more than building an RPC JSON API, and about how to make APIs more robust. This included learning about fundamental aspects of the web architecture like caching, ETAGS and content negotiation. The learning also included the hidden jewel of REST APIs, hypermedia, and new media types like HAL, CollectionJson and Siren that were designed specifically for hypermedia-based systems.

It was clear looking at our existing Microsoft frameworks that they did need meet the requirements for building APIs that really leveraged HTTP and took advantage of the web architecture. Looking within the .NET OSS community, solutions like Open Rasta, however were explicitly designed with this in mind. There were also a ton of other options outside the .NET world in Java, Ruby, Python and PHP, and more recently in node.js.

After soaking this all in, my team at Microsoft, and a team of fantastic advisors from the community, worked together to create a new framework that was designed from the get-go to fully embrace HTTP, to enable, but not force building a RESTful system.

As part of this we had an explicit goal from day one to ensure this framework would also enable building a fully hypermedia based system. Another explicit goal was to make the framework easier to test, and to allow it to work well with agile development. This framework ultimately became what you now know as ASP.NET Web API.

Although ASP.NET Web API had the foundations in place to enable such systems, you have work to do. I am not going to say that it naturally leads you to build a hypermedia system. This was not an accident. We deliberately did not want to force people down a specific path, we wanted to make sure though if you wanted to build such a system, it wouldn’t fight you.

We saw a lot of folks jump on this, even internally, folks like the Office Lync Team that built probably one of the largest pure hypermedia APIs in existence using Web API.  Many of these early adopters had the advantage of working directly with our team. They worked with me, and Henrik Nielsen (My Web API architect, and one of the creators of HTTP) to help guide them down the path. We did a lot of educating on HTTP, API fundamentals and what hypermedia is and how to build systems that support it.

On the outside we also saw a lot of energy. Folks like our advisory board jumped in and started doing the same in the wild. They built real systems, and they guided customers.

All of this work (including shipping Web API) definitely succeeded in help raising the bar around modern API development and hypermedia in the industry in general. More and more folks including some of the largest companies started coming out of the woodwork and saying, we want to build these types of systems.

However, many folks, in particular in the .NET community, have not crossed this chasm yet and do not understand how or why to build such systems. In particular building a hypermedia-based system is a sticking point. Many are scared by the term and don’t understand what it is. Others dismiss it as purely academic. Even those that do grasp the concepts often do not know where to start to implement them. This last point makes total sense, taking into consideration the points I mentioned earlier that ASP.NET Web API does not lead you toward building such APIs, it enables it.

With this book we wanted to change that. We wanted to bring these API techniques to the masses. We wanted to show you why and how to actually build these APIs with ASP.NET Web API. We wanted to show you how to make the underlying architecture of the framework to work with you in achieving that goal.

I believe we’ve done that. We look forward to your experiences with the book as you embark on API development with ASP.NET.


Darrel Miller: Implementing Conditional Request Handling for your API


In the previous post in this series on Conditional Requests I introduced the topic of validators, their purpose and how they can be constructed.  A large chunk of the work that needs to be done to support conditional requests is done by the origin server.  This blog post is about that role.

ForkInRoad

The first job of the origin server is to return a validator header along with responses for resources that want to support conditional requests.  The second function it performs is when it receives a conditional request it needs to decide if it is going to fulfill the request or fail.  A server can recognize a conditional request because there is a request header that starts with If-. Which if- header is used depends on the type of validator being using and the type of HTTP method being used.  The following if- headers are lists in the message headers repository:


  • If-Match
  • If-Modified-Since
  • If-None-Match
  • If-Range (rfc7233 – Range Requests)
  • If-Schedule-Tag-Match (rfc6638 - CALDAV)
  • If-Unmodified-Since

The If-Range and If-Schedule-Tag-Match are slightly different cases that we can save for discussion on a different day.

For reads…

For safe requests like GET the goal is to only return a response body if it has changed from what has previously been retrieved.  Therefore we use the If-none-match header with an Etag or the if-modified-since header with a Last-modified validator.  If these pre-conditions fail, then the 304 – Not modified header is returned.

Book

The if-none-match is named the way it is because a client can actually send multiple Etag values.  This can be used when a cache is holding multiple different variant representations and it only wants to receive an update if all of its variants are out-of-date. 

When comparing validators for the purpose of deciding to read or not, a “weak” comparison is used.  This means that both strong and weak validators are compared and are considered equal if the validator values are the same.

For writes…

For unsafe requests like PUT, POST, PATCH, DELETE, the conditional headers if-match and if-unmodified-since are used to abort the request if the  validators do not match. In this case the status code 412 – Precondition Failed should be returned.

Write

When comparing validators before writing,  a “strong” comparison is used.  This means that only strong validators can be used and must be equal before the request can be performed.

Bring a backup

Although a client only really needs one type of validator value to perform conditional requests, it is recommended that an origin server return both a Etag and a Last-modified header if possible.   I can only assume this is to provide support for web caches that only support HTTP/1.0.  ETags have been standardized since 1997.  It continues to amaze me how seriously the IETF folks take backward compatibility.

Clairvoyant?

The specification makes it clear that for each of the conditional request headers, the origin server must not perform the actual request behaviour if the pre-condition fails.  However, it goes on to say that

redirects and failures take precedence over the evaluation of preconditions in conditional requests

This infers that you needs to do just enough of the request processing to know that it will produce a success status code, before testing the the pre-condition and performing the request.  This has some significant implications on how you might be able to implement conditional request handling.  The specification says,

a recipient cache or origin server MUST evaluate received request preconditions after it has successfully performed its normal request checks and just before it would perform the action associated with the request method.

The part I find interesting about this last quote is the distinction between “request checks” and the “action associated with the request method”  It would be valuable to further explore this distinction and understand what checks need to be performed before pre-conditions can be evaluated.

Precedence

If you consider each of the individual elements of the entire conditional request handling process in isolation, each piece is fairly straightforward.  However, the HTTP specification puts no limitations on the ability to send multiple different conditional headers at the same time.  In order to produce sane results there specification lays out a set of rules as to the order in which these conditional headers should be evaluated.  I have simplified the rules a little by ignoring the possibility of If-Range headers, and the end result is the diagram below.

image

If you follow the flow chart through and reach the GO symbol, that means that the actual request can be performed.

Don’t fail if you don’t have to

One interesting area that I was not previously aware of until I created this diagram was the step that takes place after an Etag fails to match or the If-Unmodified-Since fails.  If some other request has already made the same change that the current conditional request is trying to make, then a server should not return a 412 failure, but simply return a 2XX status.

One last piece of the puzzle

In the first article on this subject we talked about the validator values that are required to make conditional requests.  This article covers the role of the server in conditional request handling.  The next article will discuss how the client can make conditional requests.

Image credit: Fork https://flic.kr/p/kUFSi7
Image credit: Book https://flic.kr/p/8JBSSW
Image credit: Writing https://flic.kr/p/5WtwEy


Filip Woj: Over 100 ASP.NET Web API samples

As you might now by now, last month my ASP.NET Web API 2 Recipes book was released by Apress. The book contains over 100 recipes covering various Web API scenarios that aim to help you save some headaches when working … Continue reading

The post Over 100 ASP.NET Web API samples appeared first on StrathWeb.


Darrel Miller: Code Camp NYC

This weekend I had the opportunity to speak for the first time at the New York city Code Camp.  It was an excellent event with a huge turnout and an equivalently huge number of sessions.

NewYork

With fourteen different sessions happening simultaneously, attendees were spoiled for choice and I am quite sure there were plenty of people having to make difficult choices.

Web Performance

I was happy to get the chance to see Nik Molnar’s talk on Full Web Stack Performance.  I got to learn about a number of handy HTTP related utilities that I had not seen before as well as get some great insight into how the web browsers are attempting to enable jank free user experiences.

There were a loads of other sessions that I would have loved to have seen, but unfortunately I was still preparing my own talks.

Hypermedia’s Secret SauceSecretSauce2

My first talk was a demonstration of how to build native client applications that use hypermedia to drive the application workflow.  The first demo was a slightly enhanced version of the sample that I show in my Hypermedia Client/Server Dance post.

The second demo was a more involved client application that had multiple screens and has an explicit ClientState class and specialized link classes to encapsulate the interaction behaviour of the client.  This client is very much a work in progress and will continue to evolve as I try and demonstrate more hypermedia capabilities.  You can find the source code for both the demos in my Github repository.  Be warned, if you are looking for something polished, you will be disappointed!

You can find the slides for the talk here on OneDrive.

Crafting Evolvable API Responses

My second talk was on designing representations for APIs that can evolve.  I spent some time explaining the disadvantages of using object serializers to build your wire representations and then went through a variety of different representation examples that attempt to address many of the common issues when doing API design.  The slides are available here, however the commentary on the representations is currently missing from the slides and we also did a number of examples based on questions from the audience.  If you happen to live near Burlington VT, I’ll be doing this talk again next Saturday at the Vermont Code Camp.

Vermont

Kudos

I’d like to thank Steve Bohlen and Erik Stepp and the huge team of volunteers for putting on this event.  It is great to see so much participation in the developer community.


Image credit : New York https://flic.kr/p/dauWoe
Image credit : Secret Sauce https://flic.kr/p/ag8CoD
Image credit: Vermont https://flic.kr/p/8BReje


Taiseer Joudeh: Secure ASP.NET Web API 2 using Azure Active Directory, Owin Middleware, and ADAL

Recently I’ve been asked by many blog readers on how to secure ASP.NET Web API 2 using Azure Active Directory, in other words we want to outsource the authentication part from the Web API to Microsoft Azure Active Directory (AD). We have already seen how the authentication can be done with local database accounts, and social identity providers, so in this tutorial we’ll try something different and we’ll obtain the bearer access tokens from external authority which is our Azure Active Directory (AD).

Microsoft Azure Active Directory (AD) is PaaS service available to every Azure subscription, this service is used to store information about users and organizational structure. We’ll use this service as our Authority service which will be responsible to secure our Resource (Web API) and issue access tokens and refresh tokens using OAuth 2 Code flow grant.

The resource (Web API) should be consumed by a Client, so the client will be requesting the data from the resource (Web API), but in order for this request to be accepted by the resource, the client must send a valid access token obtained from the Authority service (Azure AD) with each request. Do not worry if this is not clear now, I’ll describe this thoroughly while we’re implementing this tutorial.

Azure Active Directory Web Api

What we’ll build in this tutorial?

As you noticed in the previous posts, I’m not big fan of the built in templates in Visual Studio 2013, those templates mix MVC controllers along with Web API controllers and bring confusion to the developers, so in this post I’ve decided to build simple ASP.NET Web API secured by Azure AD using Owin middle-ware components which we’ll add manually using Nuget, then I’ll build simple client (desktop forms application) which will consume this Web API.

The Source code for this tutorial is available on GitHub.

Building the Back-end Resource (Web API)

Step 1: Creating the Web API Project

In this tutorial I’m using Visual Studio 2013 and .Net framework 4.5, to get started create an empty solution and name it “WebApiAzureActiveDirectory”, then add new empty ASP.NET Web application named “WebApiAzureAD.Api”, the selected template for the project will be “Empty” template with no core dependencies, check the image below:

Web Api Azure AD Project

Step 2: Install the needed NuGet Packages

This project is empty so we need to install the NuGet packages needed to setup our Owin server and configure ASP.NET Web API 2 to be hosted within an Owin server, so open NuGet Package Manager Console and install the below packages:

Install-Package Microsoft.AspNet.WebApi
Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Microsoft.Owin.Security.ActiveDirectory

The use for the first three packages have been discussed on this post, the package “Install-Package Microsoft.Owin.Security.ActiveDirectory” is responsible to configure our Owin middle-ware server to use Microsoft Azure Active Directory to offload the authentication process to it. We’ll see how we’ll do this in the coming steps.

Step 3: Register the Web API into Azure Active Directory

Now we need to jump to Azure Management Portal in order to register our Web API (Resource) as an application in our Azure Active Directory (Authority) so this authority will accept issuing tokens for our Web API, to do so and after your successful login to Azure Management Portal,  click on “Active Directory” in the left hand navigation menu, choose your active directory tenant you want to register your Web API with, then select the “Applications” tab, then click on the add icon at bottom of the page. Once the modal window shows as the image below select “Add an application my organization is developing”.

Add App to Azure AD

Then a wizard of 2 steps will show up asking you to select the type of the app you want to add, in our case we are currently adding a Web API so select “Web Application and/or Web API”, then provide a name for the application, in my case I’ll call it “WebApiAzureAD”, then click next.

Add WebApi To Azure Active Directory

In the second step as the image below we need to fill two things, the Sign-On URL which is usually will be your base Url for your Web API, so in my case it will be “http://localhost:55577″, and the second field APP ID URI will usually be filled with a URI that Azure AD can use for this app, it usually take the form of “http://<your_AD_tenant_name>/<your_app_friendly_name>” so we will replace this with the correct values for my app and will be filed as “http://taiseerjoudeharamex.onmicrosoft.com/WebApiAzureAD” then click OK.

Important Note:

  • On production environment, all the communication should be done over HTTPS only, the access token we’ll transmit from the client to the API should be transmitted over HTTPS only.
  • To get your AD tenant name, you can navigate to to your active directory and click on the “Domains” tab.

Add Web Api To Azure Active Directory

Step 4: Expose our Web API to other applications

After our Web API has been added to Azure Active Directory apps, we need to do one more thing here which is exposing our permission scopes to client apps developers who will build clients to consume our Web API. To do so we need to change our Web API configuring using the application manifest. Basically the application manifest is a JSON file that represents our application identity configuration.

So as the image below and after you navigate to the app we’ve just added click on “Manage Manifest” icon at the bottom of the page, then click on “Download Manifest”.

Download Manifest

Open the downloaded JSON application manifest file and replace the “appPermissions” node with the below JSON snippet. This snippet is just an example of how to expose a permission scope known as user impersonation, do not forget to generate new GUID for the “permessionid” value. You can read more about Web API configuration here.

"appPermissions": [
    {
      "claimValue": "user_impersonation",
      "description": "Allow the application full access to the service on behalf of the signed-in user",
      "directAccessGrantTypes": [],
      "displayName": "Have full access to the service",
      "impersonationAccessGrantTypes": [
        {
          "impersonated": "User",
          "impersonator": "Application"
        }
      ],
      "isDisabled": false,
      "origin": "Application",
      "permissionId": "856aba87-e34d-4857-9cb1-cc4ac92a35f8",
      "resourceScopeType": "Personal",
      "userConsentDescription": "Allow the application full access to the service on your behalf",
      "userConsentDisplayName": "Have full access to the service"
    }
  ]

After you replaced the “appPermission” node, save the application manifest file locally then upload it again to your app using the “Upload Manifest” feature, now we have added our Web API as an application to the Azure Active Directory, so lets go back to visual studio and do the concrete implementation for the Web API.

Step 5: Add Owin “Startup” Class

Now back to our visual studio, we need to build the API components because we didn’t use a ready made template, this way is cleaner and you understand the need and use for each component you install in your solution, so add new class named “Startup”. It will contain the code below:

using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;

[assembly: OwinStartup(typeof(WebApiAzureAD.Api.Startup))]
namespace WebApiAzureAD.Api
{

    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
 
            ConfigureAuth(app);

            WebApiConfig.Register(config);

            app.UseWebApi(config);
        }

        private void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Audience = ConfigurationManager.AppSettings["Audience"],
                    Tenant = ConfigurationManager.AppSettings["Tenant"]
                });
        }
    }

}

What we’ve done here is simple, and you can check my other posts to understand what the need for “Startup” class and how it works.

What worth explaining here is what the private method “ConfigureAuth” responsible for, so the implementation inside this method basically telling our Web API that the authentication middle ware which will be used is going to be “Windows Azure Active Directory Bearer Tokens” for the specified Active Directory “Tenant” and “Audience” (APP ID URI). Now any Api Controller added to this Web Api and decorated with [Authorize] attribute will only understand bearer tokens issued from this specified Active Directory Tenant and Application, any other form of tokens will be rejected and HTTP status code 401 will be returned.

It is a good practice to store the values for your Audience, Tenant, Secrets, etc… in a configuration file and not to hard-code them, so open the web.config file and add 2 new “appSettings” as the snippet below:

<appSettings>
    <add key="Tenant" value="taiseerjoudeharamex.onmicrosoft.com" />
    <add key="Audience" value="http://taiseerjoudeharamex.onmicrosoft.com/WebApiAzureAD" />
  </appSettings>

Before moving to the next step, do not forget to add the class “WebApiConfig.cs” under folder “App_Start” which contains the code below:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }

Step 6: Add a Secure OrdersController

Now we want to add a secure controller to serve our Orders. What I mean by a “secure” controller that its a controller attribute with [Authorize] attribute and can be accessed only when the request contains a valid access token issued by our Azure AD tenant for this app only. To keep things simple we’ll return static data. So add new controller named “OrdersController” and paste the code below:

[Authorize]
    [RoutePrefix("api/orders")]
    public class OrdersController : ApiController
    {
        [Route("")]
        public IHttpActionResult Get()
        {
           var isAuth = User.Identity.IsAuthenticated;
           var userName = User.Identity.Name;

           return Ok(Order.CreateOrders());

        }
    }

    #region Helpers

    public class Order
    {
        public int OrderID { get; set; }
        public string CustomerName { get; set; }
        public string ShipperCity { get; set; }
        public Boolean IsShipped { get; set; }


        public static List<Order> CreateOrders()
        {
            List<Order> OrderList = new List<Order> 
            {
                new Order {OrderID = 10248, CustomerName = "Taiseer Joudeh", ShipperCity = "Amman", IsShipped = true },
                new Order {OrderID = 10249, CustomerName = "Ahmad Hasan", ShipperCity = "Dubai", IsShipped = false},
                new Order {OrderID = 10250,CustomerName = "Tamer Yaser", ShipperCity = "Jeddah", IsShipped = false },
                new Order {OrderID = 10251,CustomerName = "Lina Majed", ShipperCity = "Abu Dhabi", IsShipped = false},
                new Order {OrderID = 10252,CustomerName = "Yasmeen Rami", ShipperCity = "Kuwait", IsShipped = true}
            };

            return OrderList;
        }
    }

    #endregion

Till this step we’ve built our API and configured the authentication part to be outsourced to Azure Active Directory (AD), now it is the time to build a client which will be responsible to consume this back-end API and talk to our Azure AD tenant to obtain access tokens.

Building the Client Application

As I stated before, we’ll build very simple desktop application to consume the back-end API, but before digging into the code, let’s add this application to our Azure AD tenant and configure the permission for the client to allow accessing the back-end API.

Step 7: Register the Client Application into Azure Active Directory

To do so navigate to Azure Management Portal again and add new application as we did on step 3. But this time and for this application will select “Native Client Application”, give the application friendly name, in my case I’ll name it “ClientAppAzureAD” and for the redirect URI I’ll enter “http://WebApiAzureADClient”. You can think for this URI as the endpoint which will be used to return the authorization code from Azure AD which will be used later to exchange this authorization code with an access token. No need to worry your self about this, because all of this will be handled for us auto-magically when we use and talk about Azure Active Directory Authentication Library (ADAL) toolkit.

Add Client To Azure AD

Step 8: Configure the Client Application Permissions

This step is very important, we need to configure the client app and specify which registered application it can access, in our case we need to give the client application permission to access our back-end API (WebApiAzureAD), the delegated permissions selected will be “Have full access to the service”, and if you notice this permission list is coming from the modified “appPermission” node in the JSON application manifest file we’ve modified in step 4. After you do this click Save.

Grant Permession

Step 9: Adding the client application project

Time to get back to visual studio to build the client application, You can use any type of client application you prefer (console app, WPF, windows forms app, etc..) in my case I’ll use windows form application, so I’ll add to our solution a new project of type “Windows Forms Application” named “WebApiAzureAD.Client”.

Once the project is added to the solution, we need to add some new keys to the “app.config” file which we’ll use to communicate with our Azure AD tenant, so open app.config file and paste the the snippet below:

<appSettings>
   
    <add key="ida:AADInstance" value="https://login.windows.net/{0}" />
    <add key="ida:Tenant" value="taiseerjoudeharamex.onmicrosoft.com" />
    <add key="ida:ClientId" value="1c92b0cc-6d13-497d-87da-bef413c9f26f" />
    <add key="ida:RedirectUri" value="http://WebApiAzureADClient" />
    
    <add key="ApiResourceId" value="http://taiseerjoudeharamex.onmicrosoft.com/WebApiAzureAD" />
    <add key="ApiBaseAddress" value="http://localhost:55577/" />
    
  </appSettings>

So the value for “ClientId” key is coming from the “Client Id” value for the client we defined in Azure AD, and the same applies for the key “RedirectUri”.

For the value for “ApiResourceId” and “ApiBaseAddress” both values are coming from the back-end API application we already registered with Azure AD.

Step 10: Install the needed Nuget Packages for the client application

We need to install the below Nuget packages in order to be able to call the back-end API and our Azure AD tenant to obtain tokens, so open package manager console and install the below:

PM> Install-Package Microsoft.Net.Http
PM> Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory

The first package installed is responsible to HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages.

The second package installed  represents Azure AD Authentication Library (ADAL) which is used to enable a .NET client application to authenticate users against Azure AD and obtain access tokens to call back-end Web API.

Step 11: Obtain the token and call the back-end API

Now it is the time to implement the logic in the client application which is responsible to obtain the access token from our Azure AD tenant, then use this access token to access the secured API end point.

To do so, add new button on the form and open “Form1.cs” and paste the code below:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        Uri redirectUri = new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]);

        private static string authority = String.Format(aadInstance, tenant);

        private static string apiResourceId = ConfigurationManager.AppSettings["ApiResourceId"];
        private static string apiBaseAddress = ConfigurationManager.AppSettings["ApiBaseAddress"];

        private AuthenticationContext authContext = null;

        private async void button1_Click(object sender, EventArgs e)
        {

            authContext = new AuthenticationContext(authority);

            AuthenticationResult authResult = authContext.AcquireToken(apiResourceId, clientId, redirectUri);

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

            HttpResponseMessage response = await client.GetAsync(apiBaseAddress + "api/orders");
          
            string responseString = await response.Content.ReadAsStringAsync();
           
            MessageBox.Show(responseString);

        }
    }

What we’ve implemented now is the below:

  • We’ve read bunch of settings which will be used to inform the client application what is the Uri/name for Azure AD tenant that it should call, the client id we obtained after registering the client application in Azure AD. As well we need to read the App Id Uri (ApiResourceId) which tells the client which Web API it should call to get the data from.
  • We’ve created an instance of the “AuthenticationContext” class, this instance will represent the authority that our client will work with. In our case the authority will be our Azure AD tenant represented by the Uri https://login.windows.net/taiseerjoudeharamex.onmicrosoft.com.
  • Now we’ll call the method “AcquireToken” which will be responsible to do internally the heavy lifting for us and the communication with our authority to obtain an access token. To do so and as we are building client application we need to pass three parameters which they are: a. The resource which the token will be sent to, b. The client id. c. The redirect uri for this client.
  • Now you will ask your self where the end user using this system will enter his AD credentials? The nice thing here that the AuthenticationContext class which is part of ADAL will take care of showing the authentication dialog in a popup and do the right communication with the correct end point where the end user will be able to provide his AD credentials, there is no need to write any extra single line of code to do this, thanks for the nice abstraction provided by ADAL. We’ll see this in action once we test the application.
  • After the user provides his valid AD credentials, a token is obtained and returned as property in the “AuthenticationResult” response along with other properties.
  • Now we need to do an ordinary HTTP GET method to our secure end point (/api/orders) and we’ve to pass this obtained access token in the authorization header using a bearer scheme. If everything goes correctly we’ll receive HTTP status code 200 along with the secured orders data.

Step 12: Testing the solution

We are ready to test the application, jump to your solution, right click on Web Api project “WebApiAzureAD.Api” select “Debug” then “Start New Instance”, then jump to your desktop application and do the same, start new instance of the EXE, click on the button and you will see the ADAL authentication dialog popups as the image blow.

ADAL Auth Window

Fill the credentials for an AD user registered in our tenant and click sign in, if the credentials provided is correct you will receive an access token as the image below, this access token will be sent int the authorization header for the GET request and you will receive your orders data.

Azure AD Access Token

Now if you tried to click on the button again without terminating the EXE (client app) you will notice that the ADAL authorization popup will not show up again and you get the token directly without providing any credentials, thanks to the built-in token cache which keeps track of the tokens.

If you closed the application and reopen it, then the ADAL authorization pop up will show up again, maybe this is not so convenience for end users. So to over come this issue you can use strategy called “token caching” which allows you to persist the obtained tokens and store them securely on a local protected file using DPAPI protection, this is better way to do it because you will not hit the authority server if you closed your client application and you still have a valid access token when you open the client again. You can read more about this implementation here.

Conclusion

Securing your ASP.NET Web API 2 by depending on Azure AD is something easy, if you are building an API for the enterprise which will be used by different applications, you can easily get up and running in no time.

As well the ADAL toolkit is providing us with great level of abstraction over the OAuth 2.0 specifications which makes developers life easy when building the clients, they will focus on business logic and the authentication/autherization part is will be handled by ADAL.

That’s it for now, I hope this tutorial will help you securing your ASP.NET Web API 2 using Azure AD, if you have any question or you have suggestions please drop me a comment.

The Source code for this tutorial is available on GitHub.

Follow me on Twitter @tjoudeh

Resources

The post Secure ASP.NET Web API 2 using Azure Active Directory, Owin Middleware, and ADAL appeared first on Bit of Technology.


Filip Woj: Things you didn’t know about action return types in ASP.NET Web API

When you are developing an ASP.NET Web API application, you can chose whether you want to return a POCO from your action, which can be any type that will then be serialized, an instance of HttpResponseMessage, or, since Web API … Continue reading

The post Things you didn’t know about action return types in ASP.NET Web API appeared first on StrathWeb.


Darrel Miller: HTTP in depth

Over the past few months I have written a number of posts relating to HTTP that have attempted to clarify some of the lesser understood areas of the HTTP specification and provide some practical guidance.

digbighole

Posts that are complete

Posts that are on my backlog

  • Conditional Request Handling
  • Making Conditional Requests
  • The connection header
  • Range based requests

Feedback

If there are posts in the backlog that you would like to see sooner, rather than later, feel free to ping me on twitter.  If there are other areas that think would be worth exploring in more detail, let me know.

Image credit: Digging a big hole https://flic.kr/p/8c6zD5


Darrel Miller: Using Etags and Last-modified headers to improve performance with HTTP conditional requests


In the recent update of the HTTP specification, the details of conditional requests have been split out and given their whole own specification.  Most developers I talk to are familiar with the idea of 304 Not Modified response code, but whenever we start to dig deeper everyone, myself included, are missing pieces of the puzzle. This article is one of a series of blog posts that attempts to dig in to aspects of HTTP and provide practical guidance on their usage.

WaxSeal

Conditional HTTP requests are used to perform an action, unless the target representation has changed, in which case they do something else.  There are two common ways that this mechanism is used:

  • we can prevent a client from having to download bytes that it already has.
  • we can prevent a client from making changes to a resource that has been changed by someone else since they retrieved it

Validators tell you when you should care about change

In order to make a conditional HTTP request, a special type of HTTP header called a validator needs to be sent in the response from the server.  The two validators defined by the HTTP specification are Etag and Last-modified.   Validators are values that allow you to compare if two resource representations are the same. The definition of "same" depends on the flavour of validator and the opinion of the origin server.

What flavour is your validator?

Validator values are considered either strong or weak.  Strong validators tell you if the response body is identical. Weak validators are used to allow an origin server to group multiple slightly different representations together as equivalent.

flavours

A strong validator can be used to identify as equivalent two different representations where the headers differ.  For example, supposing you requested the same resource as text/plain and then as text/html. If the server supported returning both of those media types, then both representations could have exactly the same body bytes and therefore returning a 304 Not modified would be feasible for the second request.  However, the origin server does have the option of changing the validator value if it believes the changed header is semantically significant.

Weak validators are used to deliver new content to a client when the representation has significantly changed, based on what the origin server deems significant.  This capability is interesting because it can enable a server to manage load on a server, by controlling how often it signals that a resource representation has changed.  This might be useful if clients are aggressively polling for changes to a representation.  The server can effectively lie to clients for a short period of time and return 304 in order to reduce the amount of bytes being delivered by the server.

Weak validators can also be used to identify equivalence between two representations that are functionally equivalent.  For example, a cache might contain a compressed copy of a representation and when it receives a conditional request for an uncompressed copy, it can identify that the client already has an up to date version of the representation even though the body bytes do not match.  This saves a cache from having to hold a cached copy of both the compressed and uncompressed version. 

Last Modified validator

The Last-modified header is simply a date and time using the HTTP date format. The value is considered to be the time when the representation was last changed.   The Last-modified validator is normally considered a weak validator because the HTTP date format only has the resolution of one second and it is often possible for multiple different representations to be retrieved within one second.  However, there are scenarios where a Last-modified header can be considered strong.

Making an Etag

There are no defined rules of how to manufacture an Etag value.  The guideline would be just to do whatever is the easiest thing that can identify a “version” of a resource representation.  Sometimes people will create a hash of the response body.  A timestamp value is another way of generating an Etag value.  If your internal entity maintains some kind of revision number, then that can be a very useful component of an Etag.  Sometimes internal entities are naturally immutable and have an internal identifier, in which case those identifiers can be used in an Etag.  It is important to remember that if there are multiple representations of the resource then the internal identifier needs to be combined with some kind of representation identifier to ensure the Etag is unique for each representation.

Making an Etag Header

An Etag header requires putting quotes around the Etag value.  There are also constraints on what characters can be an Etag value.  If you feel a burning desire to put unusual characters in your Etag value, you might want to check the spec first.  The recent update of the HTTP specification now removes the possibility of using escaped values in Etag values.

Below is a request from the Uber API with an Etag header.

UberAPIWithEtag

If you want to identify a value as a Weak Etag then you simply put W/ in front of the quoted Etag value.

Putting your validators into use

When I started this post, I had intended to make this a single post.  The more I read RFC 7232, the more I realized there is way more that needs to be said about handling conditional requests and making conditional requests, so I’m going to leave those discussions for follow-up posts.  In the meanwhile, if you are hungry for more HTTP insight, I’ve made an index of the HTTP related posts that I have done to-date.

Image credit: Wax seal https://flic.kr/p/7piVnt
Image credit: Flavors https://flic.kr/p/nm6sps


Darrel Miller: Caching resources with query strings

This afternoon Scott Hanselman posted a fairly innocuous question on twitter.  However, the question involved versioning of a RESTful API, which is a subject that is sure to bring out lots of opinions.  This post is less about the versioning question and more about the commonly held belief that caches do things differently with URLs that have query strings.

Query strings deserve more love

Putting a version number into a query string parameter is actually quite an interesting idea.  For one, it can be made optional, so that a consumer can choose to always consume the latest version, or request a specific version.  Secondly, I like it because I can selectively version just the resources that I want to.  The part I dislike about putting a version as the first segment of the URL is that it blindly versions every resource in the API whether there has been breaking changes or not.   Putting a version at the end of the URL is much better, but putting it in the path can be tricky for both client and server implementations.  Particularly if you are not using hypermedia.

Caching is king

The last reason I like the version number in the query string is that it makes the specific version a separately cacheable resource.

When I mentioned my opinion to Scott on twitter, @jeremymiller responded with,

This is not the first time that I’ve heard this guidance.  In the past when I investigated this, I discovered that a number of the HTTP caches provide configuration options that allow you avoid caching resource with query string parameters from particular domains.  I recall reading about reasons like corporate proxy caches getting filled up with tiles from google maps, pushing out all the content that get high hit rates with stuff that have very low hit rates.

As far as I understood, it was a configuration option that someone explicitly had to set to filter out certain sites. This didn’t seem like sufficient justification for the pervasiveness of the belief that query strings break caching.  So I decided to go hunting again.

A search for the source

My search kept bringing me back to a blog post by Steve Souders on how to update files that have been released with extremely long expiry times.  In this article Steve demonstrates when using a version number in the query string, the Squid proxy cache does not cache the static file at all.  He goes on to say that Squid can be configured to cache these files, but it is not the default behaviour.  Based on this information, he rightly suggested that people don’t use versions in their query string if they want to cache static resources.

squid

That was in August 2008.  Earlier that year, in May 2008, Squid released version 2.7 which changed their default behaviour to no longer refuse to cache URLs that contained a query string.  The Squid documentation explains the changes, and claims that one of the reasons for the change was because sites like YouTube were intentionally putting stuff in the query string to prevent caches from reducing traffic to their site.  I guess someone had investors they needed to impress Annoyed

We are six years down the road and the guidance based on a default setting in a HTTP cache is still with us, discouraging developers from using a significant architectural component of a resource identifier.

I don’t doubt that there are numerous other web frameworks and output caching mechanisms that apply similar constraints to resources with query strings.  However, these components should be under the developer’s control.  There is no need to artificially constraint ourselves to describing cacheable resources using only the path component of a URL.

Since RFC 3986 was released in 2005 the role of the query string has been well defined:

The query component contains non-hierarchical data that, along with data in the path component, serves to identify a resource within the scope of the URI's scheme and naming authority

Let us move forward and start treating query strings with the respect that they deserve.

Image Credit: Squid https://flic.kr/p/79fueL



Filip Woj: Strongly typed direct routing link generation in ASP.NET Web API with Drum

ASP.NET Web API provides an IUrlHelper interface and the corresponding UrlHelper class as a general, built-in mechanism you can use to generate links to your Web API routes. In fact, it’s similar in ASP.NET MVC, so this pattern has been … Continue reading

The post Strongly typed direct routing link generation in ASP.NET Web API with Drum appeared first on StrathWeb.


Taiseer Joudeh: ASP.NET Web API Documentation using Swagger

Recently I was working on designing and implementing a large scale RESTful API using ASP.NET Web API, this RESTful API contains large number of endpoints with different data models used in the request/response payloads.

Proper documentation and having a solid API explorer (Playground) is a crucial thing for your API success and likability by developers. There is a very informative slides by John Musser which highlights the top 10 reasons which makes developers hate your API, and unsurprisingly the top one is the lack of documentation and the absence of interactive documentation; so to avoid this pitfall I decided to document my Web API using Swagger.

Swagger basically is a framework for describing, consuming, and visualizing RESTful APIs. The nice thing about Swagger that it is really keeps the documentation system, the client, and the server code in sync always, in other words the documentation of methods, parameters, and models are tightly integrated into the server code.

ASP.NET Web API Documentation using Swagger

So in this short post I decided to add documentation using Swagger for a simple ASP.NET Web API project which contains a single controller with different HTTP methods, the live demo API explorer can be accessed here, and the source code can be found on GitHub. The final result for the API explorer will look as the image below:

Asp.Net Web Api Swagger

Swagger is language-agnostic so there are different implementations for different platforms. For the ASP.NET Web API world there is a solid open source implementation named “Swashbuckle”  this implementation simplifies adding Swagger to any Web API project by following simple steps which I’ll highlight in this post.

The nice thing about Swashbuckle that it has no dependency on ASP.NET MVC, so there is no need to include any MVC Nuget packages in order to enable API documentation, as well Swashbuckle contains an embedded version of swagger-ui which will automatically serve up once Swashbuckle is installed.

Swagger-ui basically is a dependency-free collection of HTML, Javascript, and CSS files that dynamically generate documentation and sandbox from a Swagger-compliant API, it is a Single Page Application which forms the play ground shown in the image above.

Steps to Add Swashbuckle to ASP.NET Web API

The sample ASP.NET Web API project I want to document is built using Owin middleware and hosted on IIS, I’ll not go into details on how I built the Web API, but I’ll focus on how I added Swashbuckle to the API.

For brevity the API contains single controller named “StudentsController”, the source code for the controller can be viewed here, as well it contains a simple “Student” Model class which can be viewed here.

Step 1: Install the needed Nuget Package

Open NuGet Package Manager Console and install the below package:

Install-Package Swashbuckle

Once this package is installed it will install a bootstrapper (App_Start/SwaggerConfig.cs) file which initiates Swashbuckle on application start-up using WebActivatorEx.

Step 2: Call the bootstrapper in “Startup” class

Now we need to add the highlighted line below to “Startup” class, so open the Startup class and replace it with the code below:

[assembly: OwinStartup(typeof(WebApiSwagger.Startup))]
namespace WebApiSwagger
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
           
            HttpConfiguration config = new HttpConfiguration();
            
            WebApiConfig.Register(config);

            Swashbuckle.Bootstrapper.Init(config);

            app.UseWebApi(config);

        }
    }
}

Step 3: Enable generating XML documentation

This is not required step to use “Swashbuckle” but I believe it is very useful for API consumers especially if you have complex data models, so to enable XML documentation, right click on your Web API project — >”Properties” then choose “Build” tab, after you choose it scroll down to the “Output” section and check “XML documentation file” check box and set the file path to: “bin\[YourProjectName].XML” as the image below. This will add an XML file to the bin folder which contains all the XML comments you added as annotation to the controllers or data models.

Swagger XML Comments

Step 4: Configure Swashbuckle to use XML Comments

By default Swashbuckle doesn’t include the annotated XML comments on the API controllers and data models into the generated specification and the UI, to include them we need to configure it, so open file “SwaggerConfig.cs” and paste the highlighted code below:

public class SwaggerConfig
    {
        public static void Register()
        {
            Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration);

            // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ...

            SwaggerSpecConfig.Customize(c =>
            {
                c.IncludeXmlComments(GetXmlCommentsPath());
            });
        }

        protected static string GetXmlCommentsPath()
        {
            return System.String.Format(@"{0}\bin\WebApiSwagger.XML", System.AppDomain.CurrentDomain.BaseDirectory);
        }
    }

Step 5: Start annotating your API methods and data models

Now we can start adding XML comments to API methods so for example if we take a look on the HTTP POST method in Students Controller as the code below:

/// <summary>
        /// Add new student
        /// </summary>
        /// <param name="student">Student Model</param>
        /// <remarks>Insert new student</remarks>
        /// <response code="400">Bad request</response>
        /// <response code="500">Internal Server Error</response>
        [Route("")]
        [ResponseType(typeof(Student))]
        public IHttpActionResult Post(Student student)
        {
            //Method implementation goes here....
        }

You will notice that each XML tag  is reflected on the Swagger properties as the image below:
Swagger XML Tags Mapping

Summary

You can add Swashbuckle seamlessly to any Web API project, and then you can easily customize the generated specification along with the UI (swagger-ui). You can check the documentation and troubleshooting section here.

That’s it for now, hopefully this post will be useful for anyone looking to document their ASP.NET Web API, if you have any question or you have used another tool for documentation please drop me a comment.

The live demo API explorer can be accessed here, and the source code can be found on GitHub.

Follow me on Twitter @tjoudeh

The post ASP.NET Web API Documentation using Swagger appeared first on Bit of Technology.


Darrel Miller: A drive by review of the Uber API

Uber recently announced the availability of a public API.  I decided to take it for a spin and provide some commentary.  The quick version is that it is a fairly standard HTTP API and that is both a good thing and a bad thing.

You can find the official documentation for the Uber API on their developer site.  In general the documentation is easy to read and it seems fairly comprehensive for what is, at the moment, a pretty simple API.  From what I can see, it is just a read-only API at the moment, but they do advertise that "more endpoints are coming".

uber

Versioning

The API reference document starts with this,

All API requests are made to https://api.uber.com/<version>, where version is currently v1

It is unfortunate that the Uber API developers have not spent more time at conferences like API Craft, RESTFest, APIDays, EndpointCon, where it is becoming increasingly common knowledge that putting a v1 at the front of your URI is not a best practice.  There many other more finely grained ways of doing versioning, when you really must introduce breaking changes.  Having a version number as a first path segment creates a huge cliff where potentially everything changes in v2 and can become a nightmare for client and server developers.

HTTP Status Codes

The documentation then lists the HTTP status codes.  I'm really not sure why the writers of the documentation feel the need to rewrite what is supposed to be standardized.  However, it is interesting that they chose to use 422 to distinguish between "invalid content" and a "malformed request".   It will be interesting to see how they make that distinction.

It does amuse me that they only include the 500 error in the 5XX range.  I'm pretty sure most clients are going to need to account for 502, 503 and 504 as well.  Enumerating out the response messages that a server supports is very misleading to client developers.  Clients need to be built to account for every HTTP status code because you never know what other status code returning intermediary is going to be sitting between you and the origin server.  There is no harm in defining actions based on ranges of status code values.  It's not as if every status code needs explicit handling code.

Error Messages

Once again, we have another API who has decided they need to re-invent the "error message" wheel.  There a number of efforts underway to create a standardized format, such as http-problem and vnd-error .  API providers should get behind one and not invent their own.

404

Rate Limiting

It is great that Uber has chosen to use the new 429 status code to indicate that rate limits have been exceeded and it is commendable that they have re-used the headers from the Twitter API for indicating the rate limit status.  However, it would have been nice if they could have dropped the X- as has been recommend in RFC 6648.

I'm not really sure why there is a need to return the rate limiting information on every request.  Why not provide a resource I can query when I want to know what the rate limit is.  Why send those extra bytes over the wire? 

Authentication

Reading the authentication section is almost a delight, because I almost don't need to read it.  For resources that a specific to a particular user, it is OAuth 2.  This is the way it is supposed to be with HTTP APIs.  By taking advantage of the uniform interface, all the infrastructure issues are just supposed to work the same way.  I don't need to learn anything new.  At least I shouldn't.  Unfortunately when testing the API we identified a number of nits related to the OAuth2 process.  I suspect they will be ironed out soon enough though.

For resources that are not specific to a user then you use a server_token which is supplied when you register your application.  Interestingly the documentation states that you MUST pass the token using an Authorization header using the authorization scheme Token.  This is awesome, just the way it should be done.  However, the reality is a bit different.  If you look at the tutorial example the server_token is passed as a query string parameter.  This is convenient but you may find your server_token littered throughout other peoples log files.  Both ways work, so just do the right thing!

Resources

The API documentation chooses to call these "Endpoints" in the heading but then uses the term Resource within the actual documentation page.  It's one of those things that doesn't matter once you already know what they mean, but it can be confusing for people who are new and trying understand which words are significant and which are not.

I am never very good at getting a grasp of APIs from looking through a list of URIs.  I much prefer a visual representation.  I'm used to building hypermedia APIs which are a bit easier to draw pictures of because they naturally have links between resources.  However, for non-hypermedia APIs like the Uber API I have found that a hierarchical diagram of the URI space by path segment can be a good visualization tool.

image

From what I understand from the documentation, this is how the URI space is defined.  The documentation does a decent job at explaining what each of these resources represent.

Media Typesreceipts

Unsurprisingly, the API simply returns application/json for all representations.  This means that it would be difficult for clients do anything other than use the request URI to identify the structure and semantics of the response.  Even sniffing the content to determine semantics is tricky because resources like /v1/me don't have a root object name.  Coupling representation structure to the request URI is common place within the HTTP API world, I just wish developers had a better understanding of the price that they are paying for taking this shortcut.

Caching

I am disappointed that we don't see any caching directives on the responses coming back from the API.  As all of the requests require an Authorization header it makes sense to choose not to make the responses publicly cacheable.  However, private caching would be perfectly viable for responses.  Especially for things like list of products.  Even more so considering the current performance of the API.  To retrieve the list of locations is currently taking around 350ms in my tests and once an HTTPS connection is established it drops down to around 150ms.  For a single request that isn't terrible, but I am doing this on a desktop with a decent broadband connection.

One mitigating factor is that there is an Etag on the products list, so at least it allows client to perform conditional GET requests and spare the bytes over the wire.  However, the current list of products weighs in at around 1KB so, chances are it would all fit in a network packet anyway!

Summary

In general, it is a fairly simple HTTP API, that uses techniques that most API developers will be familiar with.  I'm happy that we are starting to see some stabilization around security mechanisms, but I do wish that there was a little more forward thinking in API design in general.

Hypermedia potential

Interestingly, there is quite a bit of opportunity here to take of advantage of hypermedia to define workflows in this kind of API.  There are likely a few fairly well defined paths through the process of selecting a product, verifying the prices, determining time to arrival and then selecting a car.  Along the way, the client application accumulates state: where the user is located, what type of car they want, which driver they want and finally accept a request for pickup.  This is an ideal scenario for hypermedia as the engine of application state to accumulate the information selected by the user whilst leading them on to the next step of the process.

 

Image credit: Uber https://flic.kr/p/evc5a9
Image credit: 404 sign https://flic.kr/p/ca95Ad
Image credit: receipts https://flic.kr/p/35oDiF


Filip Woj: ASP.NET Web API 2: Recipes is out!

My long promised book, ASP.NET Web API 2: Recipes has been published by Apress last week. I announced the book a while ago, when I also tried to explain the general idea behind the book. I nshort, I really wanted … Continue reading

The post ASP.NET Web API 2: Recipes is out! appeared first on StrathWeb.


Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.