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.

Three tier architecture

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.

JSON Web Token (JWT) - OAuth Working Group

Part 1 – Securing Your Logins With ASP.Net MVC (This post)
Part 2 - Securing Web.API Requests With JSON Web Tokens

An archetectural patterns that is becoming more popular is using ASP.Net MVC with a Web.API layer servicing the web front end via angular.js or similar technology. A kind of hybrid SPA with all the benefits that ASP.Net bring to the table. This is a two part primer running through what I do to secure logins to MVC applications. In part two I will expand on this post to cover how to secure the Web.API layer utilizing the security built into ASP.Net.

If you ever go to a web site and you cannot remember your password, you will most likely have requested a password reminder. If you get sent your current password in plain text, then that is bad news. It means the website is storing passwords in plain text and if they get hacked then they will have access to those passwords, and knowing the fact that people have a tendency to use the same password on multiple sites then they could compromise multiple sites that you use. It is really important to salt and hash your passwords for storage in the database. By doing this, you can do a string comparison against the hash and not the actual password. Here I will go through the process in code.

As usual you will have a login screen asking for username (or email address) and password. I won't go into the MVC/Razor side here, just the important code.

Take in the two form values
The LookupUser method on the SecurityService is where the magic happensThis method looks up the User from the database via a UserRepository and appends the salt to the password the user has provided. I explain what salts and hashes are a little later on, but for now know they are just a random string representation of a passkey. This combination of password and salt are then passed into the GetPasswordHashAndSalt method of the PasswordHash class.The GetPasswordHashAndSalt method reads the string into a byte array and encrypts it using SHA256, then returns a string representation of it back to the calling method. This is then the hash of the salted password which should be equal to the value in the database. On line 19 of the SecurityService class the repository does another database look-up to get the User that matches both the email address and hash value. OK, so how do we get those hashes and salts in the database in the first place? When a new user account is set up you need to generate a random salt like this:-You then store the usual user details in the database along with the salt and the hashAndSalt values in place of the password. By generating a new salt each time an account is created you minimize the risk that a hacker will get the salt and regenerate the passwords from the hashAndSalt value. Now back to the login POST method on the controller. Once the user has been authenticated in the system, you need to create a cookie for the ASP.Net forms authentication to work. First create a ticket that stores information such as the user logged in.Where LoggedInUser is the valid User object we got from the database earlier. To check for a valid ticket throughout the site, you can decorate each action method with [Authorize] filter attributes, or you could do the whole site and just have [AllowAnonymous] attributes on the login controller actions. To do this for the whole site firstly add a new AuthorizeAttribute to the FilterConfig.cs file inside App_Start like this:-Then in the Application_AuthenticateRequest method to the global.asax.cs file add this:-This method will check every request coming in to see if it has a valid FormsAuthentication ticket. If it doesn't then it will redirect the user to the default location specified in the web.config file.

IIS Express Run From a Remote Machine

Sometimes running a web application using IIS Express using localhost is fine, but if you want to use the IP address and port to access it from another machine then you need to configure IIS Express. For example if you see this error
Invalid hostname
You can get to the IIS Express settings applicationhost.config by going to IISExpress\config in your documents folder. The important section of the config file are the sites listings  To access it from another machine, you need to add an extra entry for the binding like this:-But after restarting IIS Express which is accessible from the try icon you may get this  
Visual Studio error
  Usually all you need to do is start a command console as administrator and run this command:-To delete the same urlacl run this:-But sometimes that does not always work and you still cannot run the web application by its IP address. The other approach is to run Visual Studio as administrator. This can be tedious every time you start Visual Studio up, so find its executable which is usually under:-Right click the devenv.exe icon and choose properties. The select the compatibility tab. Change the Privilege Level to run as administrator like this:-
Visual Studio .exe properties
  You can also choose to change this setting for all users if you wish. Now you should be able to run your web application from another machine such as virtual machine.   Happy coding    

Using MVP with ASP.Net Web Forms

Here I am going to give a quick example of using MVP with Asp.Net Web Forms. Although I have a development history of Web forms and MVC, I have favoured MVC in the past few years mainly because it helps seperate out the application layers and allows the easier inclusion of unit testing. However my current client has a large collection of ASP.Net Web Forms applications and they have no intention of moving over to MVC. They are interested in unit testing and dependency injection frameworks, so utilising the MVP pattern with web forms was the best path to take.


The main difference between MVC and MVP is how views are handled. In MVC it is down to the controller to choose which view is to be sent to the client whereas in MVP there is no real choice the view is managed by a presenter.

Basics of MVP

Using MVP in ASP.Net Web Forms
There are two varients of MVP; Passive View and Supervising Controller. I am going to concentrate on Passive View for this article as that is what I have more experience with and I believe it allows the easier adoption of unit testing although you do end up with a larger solution. Like more traditional ASP.Net Web Forms applications, you have a main solution with web project within it. But here the web project is a pretty dumb project in regards to business logic. For this example the web project is the View. There can be any number of other projects in the solution, but the main ones are Model (class library), Presenter (class library) and Tests (class library). It is also acceptable to have a Service project and ViewModel project; but I will not touch on those here. The key aspect of communication between the View and Presenter is the use of Interfaces. In this example I am going to create a simple login page which on successfull login redirects the user to a secure home page and on failure kicks them back to an error page. Quite simple. The code behind of an aspx page implements an interface which exists in the Presenter project. This interface exposes properties on the aspx page like this:- ILoginView.csLogin.aspxLine 14: Creates an new instance of the presenter which knows about the ILoginView and IAuthorizationService interfaces (don't worry about the authorization service, it sits in the service project). Line 19: The CheckUser method is called which in turn calls the LookupUser method in the authorization service class. This is where the interaction between Presenter and Model occurs; in practice this service would be separated in to the Service project. For this to work, we need to be using an IoC (Inversion of Control)/DI(Dependency Injection) framework. I have opted to use Castle.Windsor for this. I won't delve into this code too much except to say it basically injects an instance of AuthorizationService whenever it finds IAuthorizationService. This is done via the BasePage class which is inherited by the aspx code behind class. LoginPresenter.csLine 18: If it is a valid user, the properties for the View are set on lines 23 and 29. Back to Login.aspx line 21: Now the FileName property has been set, the redirect takes the user there. As you can see there is not much going on in the View; all the logic is left to the Presenter layer to look-up the user. This separation allows the inclusion of dependency injection (a later post) and unit testing.

Simple Unit Test

Line 13: As you can see here there is a need for a Stub which like the View; implements the same interface.Because we are using an interface for the authorisation service; we can easily mock that in the tests and set the return value. Here I am using the MoQ framework. So there you have it a very simple introduction to using MVP with Web Forms. I have used this methodology on two large projects and it has given me a new respect for Web Forms. Happy coding. References:-

When I was first attracted to the Microsoft MVC Framework, one of my main ambitions was to develop using a more test driven approach. There are ways to include Unit testing with WebForms, but the friction was just too much to justify on the web projects I was involved with. As soon as I started using MVC I was amazed at how easy it was to incorporate unit testing and isolation frameworks; in a way it became more of a natural process. Here in this post I am quickly covering getting up and running with unit testing, isolation frameworks and MVC. My tools of choice are:-This example is a simple green field site; the typical File >> New Project >> MVC application. So we have our site, I want data from a database (in this example I won’t be bothering with creating a data store, which shows just how handy stubs can be). I want to run a test on the data and send it off to the view, simple stuff. In Models, I want to create a data repository, but I don’t want to code against a concrete type, I will use an interface.Here I have a simple method which in this case returns a hard coded integer. So far so good, the site compiles. I want the controller to handle this method call via an Order class like this.As can be seen there are two SOLID principles in use here. The Order is dependent on the Repository class, but this dependency is injected in to the constructor. Also it is handed an interface and not a concrete type. So my controller can call the GetTotalOrders method on the Order and let that handle the repository, but before all that I want a test in place that will make sure I am returning that data from the repository. Of course in the real world I don’t want to touch the database, and in this case I don’t even have one. Here is the unit test that stubs out the repository call.In this case I am forcing the repository to return an integer of 56, not the 55 from the concrete class. The solution compiles and the test passes.
Great, but how do we code this for the controller.This works fine, but I don’t want the Index method to be responsible of creating the Repository object, so we take that out and let the constructor handle that.Now it compiles ok, the tests run ok, but the web application fails.
This is where we need to start injecting the dependencies needed. We need both an ApplicationRegistry and Bootstrapper class.The ApplicationRegistry class reads very fluently and simply injects any occurrence of the IRepository type with the Repository concrete type. Next we need a controller factory which inherits from the MVC DefaultControllerFactory and is called from the Application_Start in the Global.asax file.Now rebuilding and running the site we successfully retrieve the value from the repository.