Role-Based security and WSE web Methods.

I wanted a way to use standard role-based security in my WSE Web Methods when passing UsernameTokens.  I came up with a way that seems to work nicely.  Just set a GenericPrincipal in the Thread.CurrentPrincipal in your UTM before you return.  The current thread will now have the GenericPrincipal and all your declaritive and imperitive security checks will work as normal.  This works because the UTM is called before your web method is called so the code access security works as normal.  Here is some code:

[PrincipalPermissionAttribute(SecurityAction.Demand, Role = @"WSEUsers")]
public string GetDateString()
    return DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ", CultureInfo.InvariantCulture);

protected override string AuthenticateToken(UsernameToken token)
 if (token == null)
  throw new ArgumentNullException();
 // Your DB lookup logic.
 UserDB db = Service.UserDB;
 User user = db.FindUser(token.Username);
 if ( user == null )
  return null;
 string v = db.DecryptEV(user.EV);

 // Set the principal to a generic one.
 GenericIdentity gi = new GenericIdentity(user.UserName);
 GenericPrincipal gp = new GenericPrincipal(gi, user.Roles);
 token.Principal = gp;
 Thread.CurrentPrincipal = gp;
 return v;

When using the standard/default UsernameTokenManager, this will not work as the default UTM does not set the CurrentPrincipal to anything.  However, you could make explicit checks inside the web method before continuing.

The nice thing is now you can use declaritive or imperitive security like you may be doing already.  Naturally, you can also use the Policy file.  However I still find looking a bunch of XML like a trip to the dentist.  And you have to struggle with the doco to figure out what goes where and no intellisense to help you.  I wonder about lingering GenericPrinciple object on the current thread however.  If the thread is reused by WSE, does it null the pricipal before going again?  I wonder if you need to null the priciple before the web method returns to be safe?  I would hope not, but something worth looking into.


This entry was posted in Uncategorized. Bookmark the permalink.