Friday 4 July 2014

ASP.NET database role provider for Azure Web Role application

When developing Microsoft Azure based Web applications, there can be cases when the application needs information about the user like Role, Age, other "Claim" etc. Ideal solution will be to plug-in Windows Identity Foundation (WIF) module and fetch the information from a trusted source e.g. your own ADFS installation, or a trusted third party etc. but chances are that you don't get to use it right away - either because the required implementation of that may not be available right away or using it in development environment is expensive.

In such cases, provider model of ASP.NET acts like a boon. You can plugin your custom role provider and implement the stuff based on roles/profile/claims and later on plug-in the actual provider. One example is to use AspNetSqlRoleProvider.

Set up the out of box authentication & authorization databases (by default named as "aspnetdb") by running the aspnet_regsql.exe present at .NET framework installation folder e.g. "C:\Windows\Microsoft.NET\Framework64\v4.0.30319". This launches a wizard and sets up a default database which can be used by AspNetSqlRoleProvider.

  1. Create a "Cloud Web Role" application using Visual Studio's Cloud template.
  2. Choose Windows Authentication when setting up the Web Application. I chose the ASP.NET MVC application for this sample but it can work with ASP.NET WebForms application too.
  3. Change the Web.Config to use AspNetSqlRoleProvider (System.Web.Security.SqlRoleProvider) to associating roles to the user.
  4. Use the out of the box Stored Procedures present in aspnetdb database e.g. "aspnet_Applications_CreateApplication", "aspnet_Roles_CreateRole", "aspnet_Users_CreateUser", "aspnet_UsersInRoles_AddUsersToRoles"  to add application, users, roles etc. 
  5. Change the Global.asax.cs to ensure that user's identity is set to his/her windows identity in debug mode - you would want to change this later based on your requirements.
  6. Change the home page to print if user belongs to a group.

Run the application in Azure Emulator and it should show the role information of the user. Quite useful.

No comments:

Post a Comment