Tag Archives: C#

Custom Role Attributes in ASP.NET MVC

Here is the code for defining and applying custom Role attributes in ASP.NET MVC. This specific example checks to see if the user is part of a given Active Directory group, but changing this to a custom validation should be fairly obvious.

Code in the controller:

[MyAuthorizeAttribute(Roles = “{AD group goes here}”)]
//ActionMethod code goes here…

Code to implement the attribute:

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

namespace MyProject.Controllers
{
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.User.Identity.IsAuthenticated)
{
UserGroups groups = new MyProject.Shared.ActiveDirectory.UserGroups(HttpContext.Current.User.Identity.Name);
var roles = ( Roles ?? string.Empty).Split(‘|’);

//if granted role exist in users group or if its admin-overload ( admin permission) for all menu
if (groups.IsInDistGroup(Roles) )
{
return true;
}
}
return base.AuthorizeCore(httpContext);
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = “~/Views/Shared/NotValid.cshtml”
};
}
}
}

When making service calls from a library…

Just in case you’re working in a C# class library project and need to make an HTTPS web service call and the project in which you’re working isn’t the root project of the solution, then you can either go through the brain damage of editing the app.config of the root project or you can explicitly set the binding and address of the service call in code, which is faster and easier than it seems:

using System.ServiceModel;
 
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
string serviceUrl = "https://www.somedomain.com/service.svc";
EndpointAddress address = new EndpointAddress(serviceUrl);
MyService.MyServiceSoapClient _myService = new MyService.MyServiceSoapClient(binding, address);
 
string result = _myService.doUsefulWork(param1, param2, param3, paramEtc);