Posts

Showing posts from 2013

Using Claims in ASP.NET Identity

Claims can simplify and increase the performance of authentication and authorization processes. I wrote about how you can use the roles stored as claims to eliminate back-end queries every time authorization takes place.  ASP.NET Identity has good support for claims-based identity and it creates several claims for you automatically when you create a new identity.  Here is how we create the identity for a new user during the log-in process

UserManager<applicationuser> userManager = new UserManager<applicationuser>(new UserStore<applicationuser>(new SecurityContext())); ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
If you inspect the Claims property of ClaimsIdentity after calling CreateIdentity you will see that there are there are three or more claims. There is a claim for the user ID, user name, identity provider and one for each role assigned. So what if you want to add some more claims? Here is an exampl…

Returning 401 HTTP Status Code on Authentication Failure in MVC 5 Web API's

The behavior of how a Web API responds to authentication/authorization exceptions has significantly changed in MVC 5. First, a little background. In a previous article I demonstrated how to create a custom AuthorizeAttribute that mixes basic authentication with forms authentication when using Web API's.   This custom attribute was designed to return an HTTP status code of 401 (Unauthorized) if authentication failed and a 403 (Forbidden) if the user is not authorized.  The example code was written as part of the SimpleSecurity Project, which was originally written to decouple and enhance the ASP.NET membership provider SimpleMembership.  I recently ported this code to work with the new ASP.NET Identity which replaces SimpleMembership in MVC 5.  It turns out that during my testing of the port I did not do a good job of testing error conditions. Bad tester.

The security pipeline in OWIN and MVC 5 has changed and the custom attribute was no longer returning 401 and 403 status codes. I…

Decoupling ASP.NET Identify From Your MVC 5 Application

For many of the same reasons I created class library that abstracts SimpleMembership I have created a class library for ASP.NET Identity.  I used the same interface I used in SimpleSecurity, which is basically the interface used by the class WebSecurity in SimpleMembership.  The beauty of this approach is that I could take my old models, views, and controllers from an application that used SimpleMembership and now just plugin the new ASP.NET Identity.  The main difference is that anywhere that the user ID that uniquely defines a member is used it is now a string instead of an integer, because that is the default for ASP.NET Identity. There are methods to have it use an integer as well and I am debating incorporating that into this class library.

All of the code for this is open source and available on the SimpleSecurity Project.  Just go to the Source Code page and download it. The class library is located in AspNetIdentity\SimpleSecurity.AspNetIdentity.  The filters for authorization…

Adding Email Confirmation to ASP.NET Identity in MVC 5

In a previous article I demonstrated how to customize the user profile information in ASP.NET Identity.  Specifically I showed how to add capturing an email address for the user. We will expand on this work and add email confirmation to the registration process.  This process will send an email to the user with a link they can click on to confirm their registration and log in to the system. Prior to confirmation they will not be able to log in.  This process will be similar to the one I described for adding email confirmation to SimpleMembership.

First we need to modify the user information to store a the confirmation token and a flag indicating whether confirmation was completed or not.  So now our ApplicationUser looks like this.

public class ApplicationUser : IdentityUser { public string Email { get; set; } public string ConfirmationToken { get; set; } public bool IsConfirmed { get; set; } }
If you have already made changes to the ApplicationUser…

Upgrading a Web Application Using SimpleMembership to ASP.NET MVC 5

I recently tried to upgrade the SimpleSecurity reference application from MVC 4 to MVC 5 and ran into some issues.  SimpleSecurity encapsulates and decouples SimpleMembership from your ASP.NET application and the underlying issue was compatibility with the WebMatrix assemblies that SimpleMembership uses and the new assemblies for MVC version 5, Web API version 5, and Razor version 3.

I followed the instruction for upgrading to MVC 5 that are posted here and received this error on application start.
Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)' failed.

I did some research and found that others were having the same issue. Well it turns out I did not follow the instructions exactly.  Here is one note in the instructions I did not pay close attention to.

Note: Microsoft-Web-Helpers has been replaced  with Microsoft.AspNe…

Customizing ASP.NET Identity in MVC 5

For those of you that follow my Blog you know that one of the subjects I write a lot about is customizing SimpleMembership for ASP.NET security in web applications and some of you have been asking if I have tried using it with Visual Studio 2013 RC or Preview.  Recently I have taken the time to explore using SimpleSecurity and SimpleMembership with VS 2013 RC and more recently the final release now available to MSDN Subscribers.   The short of it is there are problems with upgrading to MVC 5,  which was released to coincide with VS 2013, as described in this StackOverflow QA.  You can still develop your MVC 4 applications in VS 2013 but you will miss out on some of the new features available in MVC 5 and Razor 3.

The other problem is that SimpleMembership is going away in MVC 5 as the provider for ASP.NET security.  Microsoft has gone to another membership provider called ASP.NET Identity. In this article I will start looking at how to customize ASP.NET Identity and contrast that with…

Improving Performance of SimpleMembership By Using Claims-Based Access Control

Claims-based identity and access control became first class citizens with the introduction of .NET version 4.5.  This along with integrating Windows Identify Foundation (WIF) has added some very powerful security features to .NET 4.5.  In this article I will look how we can make a simple changes to SimpleSecurity to make it more efficient and reduce the number of times we need to hit the database during authorization by retrieving some of the information we need from claims. If you are not familiar with claims there is a good introduction here.

I originally introduced the idea of  decoupling the security model from the application by creating a custom AuthorizeAttribute that accepted a resource and operation instead of a role. You can read more about it here and some later improvements here.  In these designs I override the OnAuthorization method and it looked like this.

public override void OnAuthorization(AuthorizationContext actionContext) { base.Roles = ResourceService…

Decoupling Your Security Model Revisited

I while back I wrote an article "Decoupling You Security Model From The Application Model With SimpleMembership".  In this article I proposed a design change to how the AuthorizeAttribute is used that provides a decoupled security model that is more flexible as your ASP.NET MVC application evolves.  One reader provided good comments on what he did not like about the design, with one major issues being the use of magic strings to define the resources and operations that we are authorizing against.  If you recall from the previous article we define the custom AuthorizeAttribute like this.

[SimpleAuthorize(Resource = "UserProfile", Operation = "modify")] public ActionResult ModifyUserProfile() { ViewBag.Message = "Modify Your Profile"; return View(); }
This is a valid concern so I revisited this design and came up with a solution that eliminates magic strings and will actually perform better. Here is what our Simple…

Multiple Recordings and Copying Recordings in VoiceModel

I had a couple of enhancement requests in the VoiceModel Project around making user recordings.  The first request was to allow the directory that holds the recordings to be specified as a file structure or file share. And the second request was to allow multiple recordings in a single session.  I finally got some time to look at implementing these enhancements and was pleasantly surprised that the features were already in place because of the flexibility in the VoiceModel architecture and state machine. Well, for the most part. I will explain one little change I had to make to VoiceModel to get this to work.

To test this out I updated the RecordingExample project in the VMWithExamples solution. You can get the source code here. Basically my solution was to add an On-Exit-Action to the recording state that copies the recorded file to another location.  This satisfies the request to be able to put recording in another location, including a file share.   Here is what the On-Exit-Action …

SessionAuthenticationModule Causes Strange Redirect Behavior

I was working on a web project using ASP.NET MVC 4 when I started seeing some strange behavior. Some of my AJAX calls to ASP.NET Web API services were getting redirected back to the same URL. The only difference between the original URL used to make the call and the redirected URL was changes in case sensitivity. While this could just be annoying and cause some performance issues this was causing my application real issues because the redirected web request was missing some header information.  Specifically I was using basic authentication on the calls to the Web API's and the header was missing the authentication information and therefore this was causing the requests to fail authentication/authorization.  For the life of me I could not figure out what was causing the redirects.

Then I started thinking back to what had changed in the application that may have introduced this behavior.  I had added the use of the SessionAuthenticationModule so that I could store claim information …

Decoupling You Security Model From The Application Model With SimpleMembership

Image
One of the peeves I have with ASP.NET MVC and  how security is handled is that you have to design your security model up front while you are designing your web application.  You have to determine which roles you need to have while implementing your application so that you can add them to the Authorize attribute on the controllers actions.  Here is an example of how you control access to controller actions.


[Authorize(Roles = "admin,user")] public ActionResult DoSomething() { ViewBag.Message = "Do something really spectacular."; return View(); }
Now when we want to change our security model, such as adding new roles, we have to go through the whole application changing these Authorize attributes, recompile the application, and redeploy. This coupling causes a lot of inefficiencies.

But you can customize SimpleMembership to handle this in a better way that decouples the security model form your application domain. I will demonstrate …

Using Code-First Migration With SimpleMembership

In previous posts I have written about customizing and seeding SimpleMembership, the newest membership provider used in ASP.NET MVC 4 Internet applications.  In the example in this previous post we setup a database initializer that can be set to either to a type of DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges. As the name implies DropCreateDatabaseAlways will drop the database and recreate it every time the initializer is called, which is at application start, and will run the method to seed the database after creation.  DropCreateDatabaseIfModelChanges varies in that it will only recreate the database if the database model changes in your code.  Both of these approaches work great during development and unit testing but you would not want to deploy the solution this way for production.  This is where code-first migration comes in.

Code-first migration allows you to update the database without having to recreate it and therefore loosing the data that is already in the …

Using SimpleMembership With Mobile Applications In ASP.NET MVC 4

Someone recently asked on StackOverflow if you can use the SimpleMembership provider in a mobile application generated by the mobile template for ASP.NET MVC 4.  The shell of the mobile application generated by this template generates basic security, such as logging in, logging out, registration and password reset, but it uses the older ASP.NET membership and role providers.  So I thought this would be a good exercise to see if I could use the open source project SimpleSecurityto switch the mobile application to use the SimpleMembershipProvider.  SimpleSecurity helps decouple SimpleMembership from an MVC application.  It turns out that it was quite easy to add SimpleMembership to an ASP.NET MVC mobile application when using SimpleSecurity.

First add the SimpleSecurity assembly as a reference in your mobile project. You will also need to add WebMatrix.Data and WebMatrix.WebData as references. In the properties for these two assemblies set the property Copy Local to true.

Next modify yo…

Password Reset with SimpleMembership

Image
SimpleMembership is the new security provider that is bundled with ASP.NET MVC 4 when you use the Internet Template to create a new application.  In this article I will demonstrate how to add password reset to your MVC application using SimpleMembership. For this demonstration I will use SimpleSecurity, an open source project that decouples SimpleSecurity from your MVC application. The concepts in this article still apply if you do not use SimpleSecurity and you just want to use SimpleMembership directly.

The basic steps for changing a password when using SimpleMembership is to first generate a unique token that is emailed to the user as a link.  Then the user clicks on the link passing the token in the query string. The user is presented with a web page to enter the new password and when they submit it the token is verified and if it passes the new password is updated in the users membership information. This method of password reset is very flexible since it can be used to just chan…

Retrieving Confirmation Token in SimpleMembership

Image
A reader commented on my blog "Adding Email Confirmation to SimpleMembership" that they would like the ability to resend the email confirmation to users that did not receive it for whatever reason.  This seemed like a reasonable request and it is actually asked a lot on various forums.  The problem is that WebMatrix.WebData.WebSecurity does not provide a method to retrieve the confirmation token so that you can resend the email.  The token is only provided when you call CreateUserAndAccount and set requireConfirmationToken to true.  It turns out the only way to get the confirmation token in SimpleMembership is to directly query the webpages_Membership table.  I have encapsulated this functionality in the open source project called SimpleSecurity.

SimpleSecurity encapsulates WebSecurity and adds missing features like getting the confirmation token. It also decouples the security model from the ASP.NET MVC framework.  Now you can just call SimpleSecurity.WebSecurity.GetConfirm…

Create Proactive Notification Applications with VoiceModel

The latest release of VoiceModel now provides support for developing Proactive Notification Applications using a telephone.  Proactive notifications are used to notify customers of important events or information that they are interested in.  The media channel currently supported by VoiceModel is voice over the telephone.  Some notification systems also support channels such as SMS and email. An example application would be a pharmacy notifying you that your prescription is ready for pickup.  With VoiceModel you can develop a notification system once and it will run on any VoiceXML compatible IVR or Tropo.

I personally find notification systems very useful.  I like being kept being informed on events like, my Amazon order was delivered, my flight was delayed, or my kid should be bringing home a report card today. This type of notification is beneficial, but I do not like SPAM.  Do not bombard my phone with sales and advertising.  Not only is this annoying, it is illegal. Be sure to un…

Decoupling SimpleMembership From Your ASP.NET MVC Application

I recently came across a question in StackOverflow on making SimpleMembership "N-Tier Friendly".  The author of the question correctly pointed out that the code generated by the Internet template tightly couples SimpleMembership with the rest of the web application, peppering the application with code at the database level. What the author was really looking for was if anyone had taken the time to write SimpleMembership as a separate layer that he could reuse. My answer was that SimpleMembership was designed to be highly customizable and therefore any library written to decouple SimpleMembership from the application would not be reusable. That being said I thought it would be a good exercise to provide an example of how you could go about writing a library that abstracts SimpleMembership and has the features that we have covered so far in this blog, such as email confirmation and basic authentication.  And since I am making the source code available anyone can take this code…