Showing posts with label WIF. Show all posts
Showing posts with label WIF. Show all posts

Friday, May 29, 2020

SessionAuthenticationModule::OnAuthenticateRequest is broken

Relying on base class library modules should be safe. Unless it's the SessionAuthenticationModule that misses correct handling of some edge cases. Here's the story.
We use the SessionAuthenticationModule for ages. It's great and reliable in 99.99% of cases. However, there could be a case where there's something wrong with the cookie. The cookie is there but it has been somehow altered in the browser. Either it doesn't contain a valid base64 stream or the stream is valid but there's no XML inside the stream.
The problem is that the SAM first tries to decode the cookie
protected virtual void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
 HttpApplication httpApplication = (HttpApplication)sender;
 HttpRequest request = HttpContext.Current.Request;
 SessionSecurityToken sessionSecurityToken = null;
 if (!TryReadSessionTokenFromCookie(out sessionSecurityToken) && string.Equals(request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
 {
               ..
Now, guess what happens when TryReadSessionTokenFromCookie throws an exception? Well, the exception is not caught and thus it's escalated to your code. And now
  • what your code does when an exception occurs? You catch it by a top level exception handler and you possibly shows a generic error page.
  • what a user does when they see the error page? They refresh the browser.
  • is the error gone? Nope, the flawed cookie is still there
What you get is a nice stacktrace of the problem
   w System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength)
   w System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
   w System.Convert.FromBase64String(String s)
   w System.IdentityModel.Services.ChunkedCookieHandler.ReadInternal(String name, HttpCookieCollection requestCookies)
   w System.IdentityModel.Services.ChunkedCookieHandler.ReadCore(String name, HttpContext context)
   w System.IdentityModel.Services.CookieHandler.Read(String name, HttpContext context)
   w System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken)
   w System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs)
My first attempt to this was to replace the cookie handler by a custom cookie handler. It's not that obvious how to do that but anyway
public class CustomCookieHandler : System.IdentityModel.Services.CookieHandler
{
    private CookieHandler _handler; // = new ChunkedCookieHandler();

    public CustomCookieHandler(CookieHandler handler)
    {
        if ( handler != null )
        {
            this._handler = handler;

            this.Name       = handler.Name;
            this.Path       = handler.Path;
            this.RequireSsl = handler.RequireSsl;
        }
        else
        {
            throw new ArgumentNullException();
        }
    }

    // public override 

    protected override void DeleteCore(string name, string path, string domain, HttpContext context)
    {
        _handler.Delete(name, path, domain, context);
    }

    protected override byte[] ReadCore(string name, HttpContext context)
    {
        try
        {
            return _handler.Read(name, context);                
        }
        catch
        {
            return null;
        }
    }

    protected override void WriteCore(byte[] value, string name, string path, string domain, DateTime expirationTime, bool secure, bool httpOnly, HttpContext context)
    {
        _handler.Write(value, name, path, domain, expirationTime, secure, httpOnly, context);
    }
}
This could be plugged into the pipeline somewhere early with
FederatedAuthentication.FederationConfigurationCreated +=
        ( s, fede ) =>
        {
            fede.FederationConfiguration.CookieHandler = new CustomCookieHandler(fede.FederationConfiguration.CookieHandler);
        };
Case closed? Not really, looks like the base64 cookie data can be valid but what comes out is not XML and is not parsed! The exception changes to
   w System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
   w System.Xml.XmlUTF8TextReader.VerifyNCName(String s)
   w System.Xml.XmlUTF8TextReader.ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
   w System.Xml.XmlUTF8TextReader.ReadStartElement()
   w System.Xml.XmlUTF8TextReader.Read()
   w System.Xml.XmlBaseReader.MoveToContent()
   w System.IdentityModel.Services.SessionAuthenticationModule.GetKeyId(Byte[] sessionCookie)
   w System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie)
   w System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken)
   w System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs)
What this custom cookie handler should do would be then to make sure whatever is read, can be interpreted as XML further down. But this would slow down the custom cookie handler dramatically! Each time a cookie is read, it would be first tried to contain an XML by my custom code and then read as XML again by the existing code.
An ultimate solution? Delete your SAM cookies in the error page. As simple as that. A side effect is users are logged out of the application after an exception is caught by the top level exception handler.

Monday, September 17, 2018

Parsing SAML 1.1 (WS-Federation) tokens without the WSFam module

Ocassionally there's a scenario where a SAML token must be parsed without the WSFederationAuthentication module. Note that when the WSFam can be used, parsing is straightforward.

For us, it was one of our old applications that still can't be upgraded to .NET 4.5, because of reasons ;), and we wanted to drop the old WIF runtime (the one that targets older .NET versions). For someone else it can be another scenario, e.g. you have the SAML token as string and just want the IPrincipal out of the token.

The solution is to think of the token as it was the regular XMLDsig signed XML - the assertion node is signed and the signature's reference points back to it:

<?xml version="1.0"?>
<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
  <t:Lifetime>
    <wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2018-09-18</wsu:Created>
    <wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2018-09-18</wsu:Expires>
  </t:Lifetime>
  <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
    <wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
      <wsa:Address>https://foo.bar/</wsa:Address>
    </wsa:EndpointReference>
  </wsp:AppliesTo>
  <t:RequestedSecurityToken>
    <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" MajorVersion="1" MinorVersion="1" AssertionID="_assertionID" 
        Issuer="http://issuer" IssueInstant="2018-09-18">
      <saml:AttributeStatement>
        <saml:Subject>
          <saml:SubjectConfirmation>
            <saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod>
          </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Attribute AttributeName="windowsaccountname" AttributeNamespace="http://schemas.microsoft.com/ws/2008/06/identity/claims">
          <saml:AttributeValue>username</saml:AttributeValue>
        </saml:Attribute>
      </saml:AttributeStatement>
      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
          <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
          <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
          <ds:Reference URI="#_assertionID">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
            <ds:DigestValue>digest</ds:DigestValue>
          </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>signature</ds:SignatureValue>
        <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
          <X509Data>
            <X509Certificate>certificate</X509Certificate>
          </X509Data>
        </KeyInfo>
      </ds:Signature>
    </saml:Assertion>
  </t:RequestedSecurityToken>
  <t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
</t:RequestSecurityTokenResponse>
What you should do is to
  1. validate the signature
  2. accept or reject the signature's certificate
  3. parse the token to retrieve claims required to create the IPrincipal
The code is rather simple, what's interesting however is that the SignedXml class has to be inherited to have the signature validator that follows the AssertionID attribute (the default convention is that the signed node's id attribute is called just ID and the default validator just won't find the node that has the id attribute called differently):
    public class SamlSignedXml : SignedXml
    {
        public SamlSignedXml(XmlElement e) : base(e) { }

        public override XmlElement GetIdElement(XmlDocument document, string idValue)
        {
            XmlNamespaceManager mgr = new XmlNamespaceManager(document.NameTable);
            mgr.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512");
            mgr.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
            mgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

            XmlElement assertionNode = 
                   (XmlElement)document.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/"+
                                                         "trust:RequestedSecurityToken/saml:Assertion", mgr);

            if (assertionNode.Attributes["AssertionID"] != null &&
                string.Equals(assertionNode.Attributes["AssertionID"].Value, idValue, StringComparison.InvariantCultureIgnoreCase)
                )
                return assertionNode;

            return null;
        }
    }
Note that the XPath assumes the token has the RequestSecurityTokenResponseCollection in the root, make sure your tokens follow this convention (in case of a single token, the collection node can be missing and the token's root could be just RequestSecurityTokenResponse, update the code accordingly).

The validation code is then

// token is the string representation of the SAML1 token
// expectedCertThumb is the expected certificate's thumbprint
protected bool ValidateToken( string token, string expectedCertThumb, out string userName )
{
 userName = string.Empty;

 if (string.IsNullOrEmpty(token)) return false;

 var xd = new XmlDocument();
 xd.PreserveWhitespace = true;
 xd.LoadXml(token);

 XmlNamespaceManager mgr = new XmlNamespaceManager(xd.NameTable);
 mgr.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512");
 mgr.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
 mgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion");

 // assertion
 XmlElement assertionNode = (XmlElement)xd.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/saml:Assertion", mgr);

 // signature
 XmlElement signatureNode = (XmlElement)xd.GetElementsByTagName("Signature")[0];

 var signedXml = new SamlSignedXml( assertionNode );
 signedXml.LoadXml(signatureNode);

 X509Certificate2 certificate = null;
 foreach (KeyInfoClause clause in signedXml.KeyInfo)
 {
  if (clause is KeyInfoX509Data)
  {
   if (((KeyInfoX509Data)clause).Certificates.Count > 0)
   {
    certificate =
    (X509Certificate2)((KeyInfoX509Data)clause).Certificates[0];
   }
  }
 }

 // cert node missing
 if (certificate == null) return false;

 // check the signature and return the result.
 var signatureValidationResult = signedXml.CheckSignature(certificate, true);

 if (signatureValidationResult == false) return false;

 // validate cert thumb
 if ( !string.IsNullOrEmpty( expectedCertThumb ) )
 {
  if ( !string.Equals( expectedCertThumb, certificate.Thumbprint ) )
   return false;
 }

 // retrieve username

 // expires = 
 var expNode = xd.SelectSingleNode("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:Lifetime/wsu:Expires", mgr );

 DateTime expireDate;

 if (!DateTime.TryParse(expNode.InnerText, out expireDate)) return false; // wrong date

 if (DateTime.UtcNow > expireDate) return false; // token too old

 // claims
 var claimNodes =                 
   xd.SelectNodes("//trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/"+
                  "saml:Assertion/saml:AttributeStatement/saml:Attribute", mgr );
 foreach ( XmlNode claimNode in claimNodes )
 {
  if ( claimNode.Attributes["AttributeName"] != null && 
              claimNode.Attributes["AttributeNamespace"] != null &&
       string.Equals( claimNode.Attributes["AttributeName"].Value, "name", StringComparison.InvariantCultureIgnoreCase ) &&   
                     string.Equals( claimNode.Attributes["AttributeNamespace"].Value, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims", StringComparison.InvariantCultureIgnoreCase ) &&
         claimNode.ChildNodes.Count == 1 
      )
  {
   userName = claimNode.ChildNodes[0].InnerText;
   return true;
  }
 }

 return false;
}
A couple of comments here.

First, the XPath could possibly be shortened to reflect the possibility of a missing collection node.

Then, the code assumes there's the name claim that contains the username but it could be the windowsaccountname or maybe yet another claim type.

Friday, June 14, 2013

FederatedPassiveSignIn for WIF and ASP.NET 4.5

With WIF now fully integrated into the Base Class Library, people (including myself) found it disappointing that the FederatedPassiveSignIn control (and other ASP.NET controls) has been removed from the API.

Not only this means that the migration is not easy but also it makes it more difficult to build applications which target multiple STSes.

This is my attempt to bring the FederatedPassiveSignIn back for the community.

Go to online repository and download source code.

Thursday, September 6, 2012

SessionAuthenticationModule and dynamic authorization

In my last blog post I’ve described a method to replace the FormsAuthenticationModule with the SessionAuthenticationModule. As it turned out, the SessionAuthenticationModule has some advantages over the forms module. Please refer to the article for more details.

Specifically, the last part of the article is about authorization. What I said is that you can create your roles as claims and the module will serialize roles into the authentication cookie. Then, upon each request the user roles are retrieved from the cookie.

Forms authentication have a clear distinction between static and dynamic role management scenarios - each role provider has the CacheRolesInCookie property (http://msdn.microsoft.com/en-us/library/system.web.security.roles.cacherolesincookie.aspx) which switches between static and dynamic management: when the property is false, the role provider fires at each request, when it is true, roles are cached in a cookie.

Note that from the two scenarios, the latter (storing roles in a cookie) is a direct counterpart of our SessionAuthenticationManager scenario, where roles (claims of type Role) were cached in a cookie.

But what if you want to have your roles assigned dynamically, upon each request? Not only just when you authenticate a user for the first time?

The answer is – create your own claims authentication manager. In theory, the authentication manager fires at each request in the processing pipeline and allows you to inject custom claims to existing identity. I’ve blogged about it some time ago.

The practice is, unfortunately, slightly different. In fact, the authentication manager does not fire at each request! This is because the implementation of the SessionAuthenticationModule contains a strong condition:

// SAM class
public class SessionAuthenticationModule : HttpModuleBase
{   
  protected virtual void OnPostAuthenticateRequest(object sender, EventArgs e)
  {
    if (!(HttpContext.Current.User is IClaimsPrincipal))
    {
      IClaimsPrincipal claimsPrincipal = ClaimsPrincipal.CreateFromHttpContext(HttpContext.Current);
      ClaimsAuthenticationManager claimsAuthenticationManager = base.ServiceConfiguration.ClaimsAuthenticationManager;
      if (claimsAuthenticationManager != null && claimsPrincipal != null && claimsPrincipal.Identity != null)
      {
        claimsPrincipal = claimsAuthenticationManager.Authenticate(HttpContext.Current.Request.Url.AbsoluteUri, claimsPrincipal);
      }
      HttpContext.Current.User = claimsPrincipal;
      Thread.CurrentPrincipal = claimsPrincipal;
    }
  }
}

You see the condition in the provided implementation? If the current user is not an claims principal then fire the authentication manager.

When does it happen? There are two possible scenarios:

  • the user is not yet authenticated
  • the user is authenticated by another authentication module (like the forms authentication module)

The third scenario: the user is authenticated by the SessionAuthenticationModule is not handled by this condition! The claims authentication manager will not run.

To fix this and have the manager executed even when a user is authenticated and the identity comes from the SAM, I just have to provide a counterpart implementation:

public class Global : System.Web.HttpApplication
{
    void Application_PostAuthenticateRequest( object sender, EventArgs e )
    {
        // handle the missing scenario
        if ( HttpContext.Current.User is IClaimsPrincipal )
        {
            IClaimsPrincipal claimsPrincipal = HttpContext.Current.User as IClaimsPrincipal;
            ClaimsAuthenticationManager claimsAuthenticationManager = 
                FederatedAuthentication.ServiceConfiguration.ClaimsAuthenticationManager;
            if ( claimsAuthenticationManager != null && 
                 claimsPrincipal != null && claimsPrincipal.Identity != null )
            {
                // and execute the manager
                claimsAuthenticationManager.Authenticate( HttpContext.Current.Request.Url.AbsoluteUri, claimsPrincipal );
            }
            //HttpContext.Current.User = claimsPrincipal;
            //Thread.CurrentPrincipal = claimsPrincipal;
        }
    }

As you can see, this was added to the global application class and is merely a copy-paste from the SAM’s implementation but what I change is the condition – the condition is complementary to the one from SAM. The authentication manager is always executed then – first two described scenarios are handled by SAM, the last one – by this snippet above.

Ultimately, the claims authentication manager can be used now to manage roles dynamically as role claims can be dynamically injected in each separate request in the processing pipeline.

Wednesday, September 5, 2012

Forms Authentication revisited

Forms authentication is an authentication module, known for years and quite reliable. The core idea is that the authentication pipeline takes the so called forms authentication cookie, decrypts the cookie and sets the HttpContext.Current.User for a request. Forms authentication subsystem contains an API which can issue cookies, in particular you can attach a small portion of custom data to the cookie so that the data is available as long as the user is logged in.

Issues

There are two common issues around the Forms authentication module: the custom data cannot be too long and because it is a string – there is no natural way to make it “compound” (contain a structure of few fields).

The second issue can possibly be solved by creating your own structure (XML for example), serializing and deserializing the data. Nothing out of the box.

However, I haven’t found any solution to the the first issue. Let’s face it:

string ReallyLongUserData
{
    get
    {
        Random r = new Random();
 
        StringBuilder sb = new StringBuilder();
 
        while ( sb.Length < 8192 )
            sb.Append( r.Next().ToString() );
 
        return sb.ToString();
    }
}
 
...
 
// create a forms cookie with really long userdata (>8192)
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1, txtUserName.Text, DateTime.Now, 
    DateTime.Now.AddMinutes( 20 ), false, ReallyLongUserData );
 
HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName );
cookie.Value = FormsAuthentication.Encrypt( ticket );
this.Response.AppendCookie( cookie );
 
Response.Redirect( this.Context.Request.QueryString["ReturnUrl"] );

Guess what happens if you run this.

The answer is: the cookie is signed and encrypted and appended to the response. But apparently, the cookie size clearly exceedes the maximum size of the cookie browsers can handle. Most browsers ignore the cookie then! The cookie is missing from subsequent requests.

SessionAuthenticationModule for the rescue!

If there’s a way to replace the FormsModule with a custom module capable of handling multiple cookies, then the cookie size issue would just be gone. Let the module just split the long value to multiple cookies, TheCookie1, TheCookie2, … and then, at the server, join the cookie data and recreate the identity. And what if the module supports multiple userdata entries, a dictionary which maps keys to values possibly?

Sounds great?

Well, there IS such module. It is called SessionAuthenticationModule.

It is part of the Windows Identity Foundation and normally it is used in federation scenarios where identity cookie is issued according to SAML tokens from identity providers (here it doesn’t really matter what a SAML token is). If you work with WIF, you know the module.

However, the SessionAuthenticationModule can be used in a normal application, just to replace the incapable Forms module and provide additional features.

First, the configuration:

<configuration>
 
    <configSections>
        <section name="microsoft.identityModel" type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </configSections>
 
    <system.web>
 
        <authentication mode="Forms">
            <forms loginUrl="LoginPage.aspx" />
        </authentication>
        
        <authorization>
            <deny users="?"/>
            <allow users="*"/>
        </authorization>
 
        <httpModules>
            <add name="SessionAuthenticationModule" 
                 type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, 
                       Microsoft.IdentityModel, Version=3.5.0.0, 
                       Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </httpModules>
 
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
 
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules>
            <add name="SessionAuthenticationModule" 
                 type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, 
                       Microsoft.IdentityModel, Version=3.5.0.0, 
                       Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />
        </modules>
    </system.webServer>
 
    <microsoft.identityModel>
        <service>
            <federatedAuthentication>
                <cookieHandler name="ADWebFrontEndCookie" requireSsl="false" />
            </federatedAuthentication>
        </service>
    </microsoft.identityModel>
 
</configuration>

Note that I declare that I am using Forms module. This is to utilize the Forms ability to authorize Url access and redirect the browser to the login page in case of insufficient priviledges. The SAM module’s cookie name is also declared in the module’s section.

And there comes the code:

string ReallyLongUserData
 {
     get
     {
         Random r = new Random();
 
         StringBuilder sb = new StringBuilder();
 
         while ( sb.Length < 8192 )
         //while ( sb.Length < 512 )
             sb.Append( r.Next().ToString() );
 
         return sb.ToString();
     }
 }
 
...
SessionAuthenticationModule sam = 
   (SessionAuthenticationModule)
   this.Context.ApplicationInstance.Modules["SessionAuthenticationModule"];
 
IClaimsPrincipal principal = 
   new ClaimsPrincipal( new GenericPrincipal( new GenericIdentity( txtUserName.Text ), null ) );
 
// create any userdata you want. by creating custom types of claims you can have
// an arbitrary number of your own types of custom data
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.Email, "foo@bar.com" ) );
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.UserData, ReallyLongUserData ) );
 
var token = 
    sam.CreateSessionSecurityToken( 
        principal, null, DateTime.Now, DateTime.Now.AddMinutes( 20 ), false );
sam.WriteSessionTokenToCookie( token );
 
Response.Redirect( this.Context.Request.QueryString["ReturnUrl"] );
     

This code replaces the previous code – instead of issuing a Forms cookie, now I am issuing a SAM cookie.

And …. that’s it. The cookie is created, it is automatically split into smaller cookies so that the browser’s limit doesn’t break anything. Also, now I can easily create any type of custom data I want by mapping claim types to values. Note that multiple claims of the same type can be assigned to the identity.

Authorization with the SAM module

Another surprizing benefit of using the SAM module is that it simplifies role management and authorization. Upon each request, the module recreates the identity which is of type ClaimsPrincipal. This class has the IsInRole method already implemented. And the way you feed it with roles is straightforward:

IClaimsPrincipal principal = 
   new ClaimsPrincipal( 
      new GenericPrincipal( new GenericIdentity( txtUserName.Text ), null ) );
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.Email, "foo@bar.com" ) );
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.UserData, ReallyLongUserData ) );
 
// roles, stored in the cookie as claims!
principal.Identities[0].Claims.Add( new Claim( ClaimTypes.Role, "ADMIN" ) );

It turns out then that you don’t really have to change much in your application - the authorization should work, including the static authorization with authorization sections of web.config files. What you only need to provide is to add role claims when you create the principal object.

Happy coding.