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

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;

 

MVC 4 Views and Razor code (and showing an aggregation from an entity)

This is an example situation where Razor can be useful to allow code on a view: in this case, I have a view model like this one (very simplified):

public class Product
{
public Guid ProductId {get;set;}
public string Description {get;set;}

public virtual List ProductTransactions {get;set;}

}

public class ProductTransaction
{
public Guid TransactionId {get;set;}
public decimal Amount {get;set;}

public Guid ProductId {get;set;}
[ForeignKey("ProductId")]
public virtual Product Product {get;set;}

}

then, if I want to see a list of products with total amounts, in my view, I could use something like this:

<table>
  <thead>
    <tr>
      <td>
          @Html.LabelFor(x => x.Product[0].Description)
      </td>
      <td>
           @Html.LabelFor(x => x.Product[0].ProductTransactions[0].Amount)
      </td>
     </tr>
   </thead>
   <tbody>
    @foreach (var product in Model.Product) 
      {
       <tr>
         <td>
             @Html.DisplayFor(x => product.Description)
         </td>
        <td>
           @{ decimal totalAmount=0;
           foreach (var transaction in Product.ProductTransactions)
              {
                totalAmount= totalAmount+ transaction.Amount;
               }
            @Html.DisplayFor(x => totalAmount)
            }
       </td>
      </tr>
      }
    </tbody>
</table>

Of course this is not the complete code of the View, I just focused on what’s relevant to the use of code inside the view using Razor, for a specific purpose, in this case, obtain aggregation of the Amount for each one of the products in the corresponding entity (at the DB).

Cheers.