I need to do authorization and auditing on some WCF service methods. I’d like to do the processing in an attribute to avoid polluting my code. I’ve created a custom attribute using PostSharp and am wondering if this is a suitable approach or if there are any gotchas with relying on PostSharp for authorization mechanisms given that it is tweaking the MSIL?
In my WCF service class I’m using the attribute in the manner below.
[AuthoriseAndAudit(UserRoleTypesEnum.Operator)]
public JSONResult<bool> IsAliveAuthorised()
{
return new JSONResult<bool>() { Success = true, Result = true };
}
The abbreviated attribute code is as below.
using PostSharp.Aspects;
[Serializable]
public class AuthoriseAndAuditAttribute : OnMethodBoundaryAspect
{
private static ILog logger = AppState.logger;
private UserRoleTypesEnum _requiredRole = UserRoleTypesEnum.None;
public AuthoriseAndAuditAttribute(UserRoleTypesEnum role = UserRoleTypesEnum.None)
{
_requiredRole = role;
}
public override void OnEntry(MethodExecutionArgs args)
{
logger.Debug(String.Format("AuthoriseAndAuditAttribute checking {0}.", args.Method.Name));
// Get the user's session from cookie.
UserSession userSession = GetUserSession();
// Check that user is in the required role.
bool isAuthorised = (_requiredRole == UserRoleTypesEnum.None || (userSession != null && userSession.Roles.Contains(_requiredRole)));
// Write an audit table entry.
logger.Debug("Writing audit table entry.");
if (!isAuthorised)
{
logger.Warn("Not authorised for " + args.Method.Name + ".");
throw new UnauthorizedAccessException();
}
}
}
Normally I would say yes, but WCF has ways to do authorization so using PostSharp would be redundant and unnecessary work.
If you need to implement a custom authorization setup then yes, PostSharp will greatly aid in that.