Part 1 – Securing Your Logins With ASP.Net MVC
Part 2 – Securing Web.API Requests With JSON Web Tokens (This post)
In the last post I went over the techniques you can use to secure your ASP.Net MVC logins using salted hashes in the database. This post covers the web service layer and how to secure requests to service calls that are essentially exposed to the big bad web. To show what sort of layering I am discussing, here is a basic example of the various layers I have been using on a number of projects.
Once the user has been validated and allowed into the site, all service requests are done on their behalf. To make sure nobody who is not validated get access to the service calls, we implement JSON Web Tokens or JWT.
JSON Web Tokens
Jason Web Tokens are a standard and url safe way of representing claims and was created by the Internet Engineering Task Force (IETF). They are in the form like this:-
A JWT is split into 3 sections which comprise of:-
JOSE Header – this describes the token and the hashing algorithm that is being used for it.
JWS Payload – the main content and can include claims sets, issuer, expiry date as well as any bespoke data you want to include
Signature hash – base64 encoding the header and payload and creating the message authentication code (MAC) leads to the signature hash
Creating JSON Web Tokens in .Net
Going back to the web project, in the constructor of each controller, create a private field that will store our token string.
The code to generate the token uses the System.IdentityModel.Tokens.Jwt namespace which you may need to add extra references for by using the NuGet packages.
The call to Authorization.GetBytes() is a method call from a class we use in a business object that sits in the Webservice layer. All it does is turns a string into a byte array.
Here we just store the web token in the viewbag for rendering on each view, the reason we do this is because we don’t want to run into any cross domain issues as our web and web service layers are running on different machines on different urls.
Now in the angular code that is calling into the service layer we extract that token and append it to the call as a parameter.
Consuming JSON Web Tokens
In the web service layer we intercept each call by creating an override on the OnAuthorization method inside AuthorizeApi.cs within App_Start.
If they have the correct and valid token then they proceed to get the data from the API call, if not they get sent a 403 Forbidden response.