This blog simply talks about a solution to implement role based authorization in a WCF service which is exposed by using BizTalk’s WCF Service publishing wizard. In a normal WCF service implementation, authorization can be simply done by putting security attribute on Web methods as given below:
[PrincipalPermission(SecurityAction.Demand, Role = "Administrator")]
public string GetSecuredData(int id)
{
return string.Format("here is a secured data of {0}", id);
}
But when it comes to implementing authorization for WCF services which are exposed using WCF Publishing wizard, there is no way you can put any such attribute in web method. I got a solution in an article by Mohamed M Malek at Implementing Dynamic Authorization for a WCF service using SQL providers but then after doing some R&D on custom service authorization manager, I found that the solution can be simplified a bit. My version of custom service authorization manager is as below:
using System.ServiceModel;
using System.Web.Security;
using System.Security.Principal;
using System.IdentityModel.Tokens;
public class SqlAuthorizationManager : ServiceAuthorizationManager
{
protected override bool CheckAccessCore(OperationContext operationContext)
{
bool baseResult = base.CheckAccessCore(operationContext);
if (operationContext.ServiceSecurityContext.IsAnonymous)
{ return true; }
IIdentity Identity = operationContext.ServiceSecurityContext.PrimaryIdentity;
if (!Identity.IsAuthenticated)
{
throw new SecurityTokenValidationException
("Service Authorization can not be done for unauthenticated user.");
}
if (operationContext.Host.Authorization.RoleProvider != null)
{
string[] roles = operationContext.Host.Authorization.RoleProvider.GetRolesForUser
(Identity.Name);
if (roles == null || roles.Length == 0 || !roles.Contains("MyRole"))
{
throw new System.ServiceModel.Security.SecurityAccessDeniedException
("User is not authorized. Identity : " + Identity.Name);
}
}
else
{
throw new System.ServiceModel.Security.SecurityAccessDeniedException
("Service Authorization failed because role provider is missing or it is not configured properly.");
}
return baseResult;
}
}
Build your project and deploy the DLL in GAC. The below image shows how I configured my SQL Authorization manager in WCF Custom Adapter configuration.
About Me
I am an integration expert having 8 years of experience in integration space. My primary expertise lies in implementing SOA and ESB based integration platform using Microsoft BizTalk Server, .NET, WCF etc. In my blogs, I generally include topics on issues that I face in my projects and how I resolve them.
CodeProject