Posts

Showing posts from 2012

WebAPI and Subscriber Authentication by Custom HTTP Headers

Recently I've been experimenting with WebAPI, part of the ASP.NET 4 framework. Whilst providing a great way to provide HTTP services, most HTTP services that are provided by companies are on a subscription basis. With this in mind, how can I best secure my HTTP Services for consumption by a paying subscriber?

The easy answer is to pass in an authentication token or credentials with each call to your HTTP service. How you do this is important, particularly for GET methods.

The best solution I've come up with so far is to add a custom authentication header to calls to my HTTP service, and provide a mechanism in my WebAPI MVC application to check the authentication provided in the header of each call.

First, we need to build our WebAPI MVC application! To do this:

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select We…

MVC - SSL, Testing and Production

I recently had a conversation with a colleague about SSL and how a login page for an MVC application could be forced over SSL, to ensure credentials supplied in the login form are sent over an encrypted channel.

The answer is quite easy: there is a flag that can be set for your controller method calledRequireHttps

However..

During my time as a developer, one problem I have seen and witnessed many times is the one of development code being published to a production environment. The consequences of which can range from minor embarrassment (Response.Write() anyone?) to dangerous security holes.

When debugging an application, having the RequireSSL flag set for a controller method can cause all sorts of issues and the temptation is to comment out this flag for debugging. The danger here of course is that this flag is not then un-commented for deploying to a production environment.

There are several ways to ensure this doesn't happen:

1.You could use IIS and a self-signed certificate when tes…

Entity Framework 4.3 Seeding Data Using int as Identity Column Type

When seeding data using EF 4.3 code first, there is a gotcha when seeding data in identity columns. Let me explain.


In a recent project, I had two tables as part of my model. The first one was called Questions, and the code looked like:

[Table("Questions", Schema = "Forms")] public class Question { public int QuestionID { get; set; } [Required(ErrorMessage = "The question is required")] [MaxLength(400)] public string QuestionText { get; set; } public string Marker { get; set; } }
The next table was a relationship table to link Question records to a table with Form records. I had used a linking table as I needed a display order column:

[Table("FormsQuestions", Schema = "Forms")] public class FormsQuestions { [Key, ForeignKey("Form"), Column(Order = 0)] public int FormID { get; set; } public virtual Form Form { get; set; } …

ASP.NET DropDownList Postback: The jQuery AJAX Replacement for MVC

It was handy in ASP.NET WebForms to have the AutoPostback property and use the SelectedIndexChanged event, to allow other parts of your WebForm to be updated depending on user selection!

With MVC and Razor you can achieve the same functionality, but it has to be done using some other way that fits in with a View. Recently I had a requirement to render a list of checkboxes on a user form; the catch was that the list of checkboxes to be rendered was dependant on a drop down list option the user selected on the same form...
With this senario, we have three main components to any solution:
1. We need to fire a method when the drop down list selection changes. 2. This method needs to take the value of the selected item in the drop down list and return output based on that value. 3. The returned output needs to be rendered in the view.
With the requirement I had, I needed to query a database to return the data needed to render the checkboxes. The solution I used utilised jQuery AJAX and JSO…

MVC: Security Best Practises for Entity Framework 4.3 Code First and SQL Server

With Entity Framework, using code first development is a real time saver - however there are several best practises to consider when using SQL Server as your data store.


1. The user credentials you specify in the web.config when developing your application must have elevated privileges to drop/create the database depending on the database initialiser you are using for development. The use of web.config transforms for specifying different configurations for different build environments is essential, so that a connection string for a production build has user credentials with the lowest possible privileges.


2. Use DataAnnotations to specify schemas. In most of the examples I have seen, objects are created in the dbo schema. An example of how to specify a schema for your entity is:


[Table("Course", Schema = "Students")] public class Course { public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; …

MVC - Displaying CheckBoxLists for Generic Lists

When developing an application, you may encounter a scenario where you have, for example, a customer record and that customer may be a member of several (but not all) customer lists in your application. 


All fairly straightforward. In an ASP.NET WebForms application for a customer management page where you want to select or un-select the lists a customer is in, you would typically bind the available customer lists to a CheckBoxList and in the DataBound event for this CheckBoxList control you would then mark checkboxes as checked for the lists your customer is in.


Depending on how you structure your application, this could involve two calls to your data store - one to get the available customer lists and one to get the customer details.


With MVC, the approach to this scenario takes a little adjustment!


The MVC Approach

There are several ways to handle displaying checkbox lists, however when I am developing MVC applications  I prefer to work solely with the strongly typed ViewModel I have cr…

MVC3 - Securing with Authentication and Anti-forgery by Default

Following on from my post about securing MVC3 application by use of global filters, I have released today a package on nuget.org that can be installed to do this automatically.


In addition to requiring to set explicit anonymous access for controller actions you want to be accessible anonymously, there is also ad additional filter for anti-forgery tokens. The additional filter requires you to pass an anti-forgery token in every form post.


Please download the package and let me know what you think! 


https://nuget.org/packages/ValidationAndAuthenticationByDefault.MVC3/1.0.0

Securing Your MVC Intranet Applications - Security by Default

The standard way to secure your MVC Intranet applications is to use the [Authorize] attribute for controller actions you want to secure. The controller is the resource you're actually trying to protect and any security decisions should be done at the controller level rather than at the route level.


For example using the default Intranet Application template in MVC3, you will have a Home Controller that looks like the following:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace MvcAuthenticationSample.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";


            return View();
        }


        public ActionResult About()
        {
            return View();
        }
    }
}

To force users to log on when they access /Home/, you would add the [Authorize] attribute to your Index ActionResult, like this:

[Authorize…

Custom WCF Authentication Using Message Contract

When you create a WCF Service or Web Service, you may want to implement subscription based access to this service. This allows you to have many customers consuming the service, with each customer having their own account and credentials to access.

When creating ASP.NET Web Services, implementing subscription based access can be done by using the SOAP header to add credentials particular to the customer consuming the web service. In a WCF service, this is done using the Message Contract.
For this post, I have created a test WCF service application which is used to return account data for a customer. The interface has one operations contract called GetAccountsData which returns a message contract called accounts info. As the accounts info message contract has sensitive information, I am also specifying the EncryptAndSign attribution on the properties on the message contract. 
The Interface:
[ServiceContract]     public interface IAccountsService     {         [OperationContract]         Acco…

UAC Administrator Access on a Windows Server 2008 Development Server

Image
Windows Server 2008 R2 has UAC build-in and turned on by default. With a server hosting your applications that is exposed to the outside world, you definitely want to keep this feature turned on!


On an internal development server however, you may wish to disable UAC for the administrator users group as with it turned on you will find barriers when testing that can slow things down - one example is changing a value in an exe.config file in the programs directory as you won't be able to save the config file back to the same location without running the editing program in Administrator mode.


To disable UAC for the administrators group, follow these simple steps:


1. On your server, go to "Administrative Tools" > "Local Security Policy"
2. Expand the "Local Policies" > "Security Options" node and find the "User Account Control: Run all administrators in Admin Approval Mode" policy in the main window.



3. Open the policy and select the &…

SQL Server: Insert, Update and Delete Data in a Single Execution by Using MERGE

With the release of SQL Server 2008, insert, update, or delete operations can be performed in a single statement using MERGE. Prior to SQL Server 2008, each insert, update or delete had to be run separately. The MERGE statement allows you to join a data source with a target table or view, and then perform multiple actions against the target based on the results of that join. 


The following example is taken from TechNet, and the original example can be found at http://technet.microsoft.com/en-us/library/bb522522(v=sql.105).aspx This example uses MERGE to insert, update, or delete rows in a target table based on differences with the source data.


Example
==================


Consider a small company with five departments, each with a department manager. The company decides to re-organise its departments. To implement the re-organisation results in the target table dbo.Departments, the MERGE statement must implement the following changes:


Some existing departments will not change.Some existing d…