Custom attribute with WIF claims based authorization

WIF is Microsoft framework for building applications using token security services and claims. Claims are like attributes that describe the user. An example could be the claim Role with a value “Administrator”. Another example, claim Location, value “ManaguaOffice1”.

I can develop an application that can validate claims and act in consequence, like allowing access to some functionality based on Role or location claims.

You can find a nice explanation on the topic here: Introduction to claims based authentication in .Net

I’d like to share an implementation of claims based authorization. This is a solution we developed at a ASP.Net MVC 5 project that uses WIF and OWIN security. We needed to provide a simple way to set authorization for users to access application functionality based on their roles.

As the functionality users have access to is implemented using ASP.Net MVC controllers and controller’s action methods, we needed a custom attribute that could be applied to either controller or action level. We developed an alternative custom attribute, here the code:

//
//Enables custom claims based authorization.
//It uses role claim type.
//Role values get from Auth DB.
//

public class RoleAuthorizeAttribute : AuthorizeAttribute
{

private string[] claimValues;

public RoleAuthorizeAttribute(string allowedRoles)
{
claimValues = allowedRoles.Split(‘,’);

var userProfile = UserProfileRepository.Get(HttpContext.Current.User.Identity);
var identity = UserProfileRepository.AddClaimsRole(userProfile, HttpContext.Current.User.Identity);

}

public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{

bool isInRole = false;

foreach (var str in claimValues)
{
//It can manages white spaces before and after the role name.

isInRole=HttpContext.Current.User.IsInRole(str.Trim());

if (isInRole) break; //break foreach as user is in one of the required roles.
}

if (isInRole)
{
base.OnAuthorization(filterContext);
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}

}
}

This class inherits from AuthorizaAttribute class and overrides the onAuthorization action filter to allow to “inject” the custom attribute. It can work for more than one role. I’d implement it at the controller like below:

[HttpPost]
[RoleAuthorize("user, admin")]
public ActionResult MyAction(int id)
{
....

 

Cheers.

Timeout issue at Azure Scheduler

Found an issue on implementing service execution using Windows Azure Scheduler. The triggered call is a long running one. Scheduler times-out after 60 seconds, as waiting for response to request made by the job.

The solution I came out with, for my situation, was to modify service code (Web API), making method call asynchronous, so execution of the action method called by Scheduler job request continues and finished on time.

This is the code I used for calling the method asynchronously, at the Web API action method:

Task.Factory.StartNew(() => MyMethodClass.MyStaticMethod(parameter));

Details: http://social.msdn.microsoft.com/Forums/en-US/46f56a6f-204a-416f-b267-b558dbeeffa2/how-to-change-the-timeout-for-azure-scheduler-job?forum=azurescheduler

Cheers,

Danfer.

Starting the year – Improvement through creativity

First post for 2014. I made my New Year’s resolutions, professional field, creating great software with Zgura:

  1. Learn, get certified for Web development, exams 70-480, 70-486 and 70-487 link
  2. Apply SOLID development principles
  3. Always try to improve through creativity

On 3, I’d like to comment on the ideas expressed at Fareed Zakaria GPS program, in an interview to Elon Musk GPS link, summarizing, people working at his company must not just develop technology, they must improve on what has been developed. Just doing one work is not enough, need to improve on existent work.

As such, I’d like to share on an improvement I just implemented, developing on work already done by my colleagues at Zgura:

As we develop ASP.Net MVC apps and deploy continuously from Git into Azure Websites, one website for each stage of development and branch on source control (i.e., development, test, production) we wanted to set and use configuration environment variables for between other things, connection strings to databases, in Azure Websites and get them from Environment variables, using:

public static string ConnectionString
        {
            get
            {
                return Environment.GetEnvironmentVariable("APPSETTING_ConnectionString,"varname");
            }
        }

But after implementing that, we had an issue when trying to do local debugging as the application doesn’t have access to the environment variables repository. A solution I found was to add that variables at Application_Start, under Global.asax.cs:

#if DEBUG
            Environment.SetEnvironmentVariable("APPSETTING_ConnectionString","varname");

#endif

Cheers.

P.d.

As per a comment from my friend Salvador Aguilar, I’d like to show a screenshot of deployment configuration into Azure websites.

Continuous Deployment Azure

MVC 4, Keeping Convention over Configuration

I’ve found myself adding several actions methods to a controller, repeating the action method type, like for example, having more than one Index method at the controller. Of course, I add something like ProcessAIndex, ProcessBIndex, etc.

I believe that may not be according to MVC principle of convention over configuration, so think I should have more controllers. I also think I can use Areas to mitigate controllers proliferation I’ll get. Will investigate more and will keep updated.

Twitter Bootstrap Less package on MVC 4

I followed the excellent article from Maarten Sikkema, from Macaw

Very good as it shows how to use Web Essentials plugin for VS to compile Bootstrap LESS files into CSS files.

I was able to successfully publish the site to an Azure Website while keeping simple layout view. I like using a separated navigation bar partial view as to separate that part from the general layout.

 

MVC Views, Returning to the same view after edit

I’d like to share how to return the same view after adding or editing content to the current item.

I had the case where I was editing a transportation record where I can have one or more containers (in my example).

Since I’m modifying an specific transportation, in the get version of the ActionResult method, is a parameter, lets say:

 

public ActionResult Create(Guid id)
{
...
}

Once I make the addition, at the POST version of the ActionResult method, I want the user to stay at the same view, for current Transport. if I used something like:

...
return View("Create", TransportationId)
...

I got the user back to the same view (page) but he/she can still see the same values just entered before saving, which is confusing and made users to sometimes add containers records more than once. In order to solve that situation I used:

...
return RedirectToAction("Create", new {id=TransportationId})
...

RedirectToAction returns a response to the browser and causes it to make a GET request to Create Action. The new… part carries the route parameter (as parameters are included on route querystring.

This way, when users adds the container, he/she can see the same page but with empty values so can keep entering more containers without thinking previous save was not successful.

Cheers.

Una semana súper ocupada (como todas)

Pero ha sido una semana de muchos éxitos trabajando con C# y MVC 4 en la plataforma de trazabilidad de proteina para Zgura.

Hemos implementado localización, membresía y autorización. Por cierto esos son temas de nuevos posts para este blog.

Una recomendación, si alguién empieza a trabajar con MVC 4, en mi humilde opinion (IMHO) es mejor comenzar de una vez utilizando las herramientas de la plataforma (MVC 4): código primero (pertenece en realidad a Entity Framework, Code First), modelos de vistas en vez de viewbag, fuertemente tipado en las vistas (views), etc.

Utilizar las herramientas que nos da esta tecnología nos ahorra mucho trabajo, cuando la aplicación crece y se le tiene que dar mantenimiento, lo anterior es de gran ayuda.

Yes, localization working for EPPlus generated Excel files to Azure

It works (will write soon on how to implement localization in general on MVC 4). What I’ve changed on my approach is now the central provider for the names for properties, henceforth, for the field’s display names is the resource provider, which in my case, is in the Azure SQL DB.

Key is to just use [Display(Name={“Key_Name”}] in the case of the data annotations for properties and string myString=LocalizationResourceProvider.Current.GetString(“{Key_Name}”); for getting key value programmatically.

Then, for the generated Excel file, I just assign the myString to the header row:

worksheet.Cells[row,1].Value=myString;