Search

Locations of visitors to this page

Categories

On this page

Forms Auth & Federated Security (part 2)
Integrating Forms Authentication and Federated Security
SAML Token Requestor
Federation over TCP streaming

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 49
This Year: 5
This Month: 0
This Week: 0
Comments: 69

Sign In

 Saturday, April 25, 2009
Saturday, April 25, 2009 1:23:14 PM (GMT Standard Time, UTC+00:00) ( Federation/STS | WCF Security )

Here I talked about an approach that you can use to integrate your legacyJ  forms auth applications with STS and bring them into the world of federated security.   

One major hurdle in implementing this approach is to flow Forms Auth cookie to the STS so that it can authenticate the caller and can issue a token. With wsFederationHttpBinding, you don’t directly talk to the STS rather federation binding talks to the STS as part of your service call.  After wsFederationHttpBinding successfully acquired a token, only then your service is called and token is sent as part of the call. This is good because it hides all the token acquisition/forwarding complexity from you and offers you a simple programming model.

Now in our case, we need to intercept the messages sent by FedBinding to the STS so that we can send our Forms Auth cookie along with the message.

At this point a very brief diagrammatic overview of WCF message security framework will help:

On the client side TokenProvider is responsible for providing tokens to message security layer. There is TokenProvider for each type of type (Usernname, IssuedToken etc).

IssuedSecurityTokenProvider is used when a SAML token is required by the message security layer and this is the guy we need to intercept.

Let’s start by creating a custom ClientCredentials:

public class ClientCredentialsWrapper : ClientCredentials

{

    public ClientCredentialsWrapper()

    {}

    public ClientCredentialsWrapper(ClientCredentials other):base(other)

    {}

    public override SecurityTokenManager CreateSecurityTokenManager()

    {

        return new ClientSecurityTokenManagerWrapper(this);

    }

    protected override ClientCredentials CloneCore()

    {

        return new ClientCredentialsWrapper(this);

    }

}

Next our custom SecurityTokenManager:

class ClientSecurityTokenManagerWrapper : ClientCredentialsSecurityTokenManager

{

    public ClientSecurityTokenManagerWrapper(ClientCredentials parent)

        : base(parent)

    { }

    public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement)

    {

        var provider = base.CreateSecurityTokenProvider(tokenRequirement);

        var issuedProvider = provider as IssuedSecurityTokenProvider;

        if (issuedProvider != null)

            issuedProvider.IssuerChannelBehaviors.Add(new MessageInspectorInstallerBehavior());

        return provider;

    }

}

Here I have added endpoint behaviour in the ChannelFactory used by IssuedSecurityTokenProvider to talk to STS.

 

 class MessageInspectorInstallerBehavior : IEndpointBehavior

{

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)

    { }

 

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)

    {

        clientRuntime.MessageInspectors.Add(new CookieFlowMessageInspector());

    }

 

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)

    { }

 

    public void Validate(ServiceEndpoint endpoint)

    { }

}

Here I’m simply installing a MessageInspector which looks like this:

class CookieFlowMessageInspector : IClientMessageInspector

{

    public void AfterReceiveReply(ref Message reply, object correlationState)

    { }

 

    public object BeforeSendRequest(ref Message request, IClientChannel channel)

    {

        object prop = null;

        HttpRequestMessageProperty rmp = null;

        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out prop))

            rmp = prop as HttpRequestMessageProperty;

        else

            rmp = new HttpRequestMessageProperty();

 

        rmp.Headers[HttpRequestHeader.Cookie] = FormAuthUtility.GetCookieHeaderFromRequest();

        request.Properties[HttpRequestMessageProperty.Name] = rmp;

        return null;

    }

}

Client code will stay the same and you just have to call just one extension method to hook everything together.

 var proxy = new STSCookieServiceReference.EchoServiceClient();

var certPath = HttpContext.Current.Server.MapPath("~/localhost.cer");

proxy.ClientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(certPath);

 

proxy.EnableIssuedTokenProviderCookieFlow(); 

proxy.Echo("Welcome.");

And this is how extension method is implemented.

public static void EnableIssuedTokenProviderCookieFlow<TChannel>(this ClientBase<TChannel> source) where TChannel : class

{   

    var orignal = source.Endpoint.Behaviors.Remove<ClientCredentials>();

    source.Endpoint.Behaviors.Add(new ClientCredentialsWrapper(orignal));

}

I have attached complete solution with this post. Feel free to download and have a look.

 

 

Download: FormsAuthFedSecurity.zip

Comments [0] | | # 
 Wednesday, April 15, 2009
Wednesday, April 15, 2009 8:42:24 PM (GMT Standard Time, UTC+00:00) ( Federation/STS | WCF | WCF Security )

Here I have talked about a technique to flow Forms Authentication cookie to a WCF service and using it as an authentication credential for the service.  For this to work – service must be running in ASP.net compatibility mode and Forms Authentication must be configured in web.config.

Here is diagrammatic view of a simple case.

In the above diagram, website authenticates users using Forms authentication, which creates a cookie after successful authentication. When ASP.net sites calls the backend service (in response to users action) – it simply passes the Form Auth cookie as part of the call. Now because our service is running in asp.net compatibility mode and Forms Authentication module is also configured in web.config, cookie will successfully be validated and we will see correct identity in the HttpContext.User

Looking good so far. Yes?

I think, this is acceptable when you only have one to two services – however when we talk about SOA – we generally mean larger number of services and this is where this approach becomes clunky primarily due to following two reasons:

·         Every service MUST run under asp.net compatibility mode, which is slower than the default native mode. So you incur some performance plenty.

·         For the cookie flow to work, both participants MUST use the same <machineKey>.  As your share single key among more and more participants – the overall security of solution is getting weaker as key will be duplicated across many places.

So there are some scalability & security issues in the above architecture.

 Let’s see how we can improve this architecture by introducing an STS into picture. The goal here is to extract the authentication mechanism (FormsAuth cookie based) out of the services and move it to STS. Service will simply require a token from STS – it is STS’s responsibility to authenticate user using some mechanism (Forms Auth being the step one).

Here you can see ONLY STS is running in asp.net compatibility mode and services are running under native mode which will result in better performance.

Also now we are only sharing keys (<machineKey>) between two participants (STS  & Website) regardless of the number of services. Services are simply configured to require a SAML token from the STS and are agnostic to the actual client authentication mechanism. We can easily change cookie based authentication with Kerberos without impacting services at all.

Now Step 1 isn’t really possible out of box – why?

Because it’s the wsFederationHttpBinding, which talks to STS rather your proxy (configured to use wsFederationHttpBinding). So setting cookie on the proxy will NOT send it to STS and the solution is to extend WCF security framework to enable cookie flow to the STS.

In next post, I will show how to implement Step 1 while still leveraging wsFederationHttpBinding. For now please see this post for background.

 

 

Comments [1] | | # 
 Friday, July 11, 2008
Friday, July 11, 2008 2:19:13 PM (GMT Standard Time, UTC+00:00) ( Federation/STS | Geneva )

In yesterdays post I have shown you how to create a basic STS using Zermatt. You can use this STS by configuring your clients to use WSFederationHttpBinding however in that case you will never see the token issued by STS. In this post I will show you a direct way to communicate with your STS by using the IssuedSecurityTokenProvider – This is useful for quick testing scenarios or when you need access to the issued token.

TokenProviders are the WCF components which provide the tokens used in message security. There is usually a TokenProvider for each type of security token (Certficate, UserName, Kerberos, IssuedToken etc). IssuedSecurityTokenProvider internally uses a ChannelFactory to communicate with the STS to get the actual token. You can configure this ChannelFactory by adding your custom behaviors to the IssuerChannelBehaviors property of the IssuedSecurityTokenProvider. Here is the code sample.

 

public static void Main()

{

    //This provider internally creates a WCF proxy (ChannelFactory) and uses it to issues RST request.

    IssuedSecurityTokenProvider provider = new IssuedSecurityTokenProvider();

    provider.SecurityTokenSerializer = new WSSecurityTokenSerializer();

 

    provider.TargetAddress = new EndpointAddress("http://localhost/IService");

    provider.IssuerAddress = new EndpointAddress("http://localhost:9000/STS");

 

    var be = new WSFederationHttpBinding().CreateBindingElements().Find<SecurityBindingElement>();

    // use the default algo & security versions used by Federation binding.

    provider.SecurityAlgorithmSuite = be.DefaultAlgorithmSuite;

    provider.MessageSecurityVersion = be.MessageSecurityVersion;

 

    // Binding used to communicate with STS.

    provider.IssuerBinding = new WSHttpBinding();

 

    // opent the internal channelfactory.

    provider.Open();

   

    // request token by issuing a WS-Trust RST request.

    var issuedToken = provider.GetToken(TimeSpan.FromMinutes(1));

   

    // print token on the console.

    WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer(be.MessageSecurityVersion.SecurityVersion);

    var writer = XmlWriter.Create(Console.OpenStandardOutput());

    serializer.WriteToken(writer, issuedToken);

    writer.Flush();

    provider.Close();

}

 

My STS requires Kerberos token to issue a SAML token – so this provider simply uses the kerberos token of the process. If you need to send different token (UserName etc) then you can do that using the IsserChannelBehaviors propery mentioned ealier.

provider.IssuerChannelBehaviors.Add(new IssuerCredBehavior());

And custom behavior looks like this.

public class IssuerCredBehavior : IEndpointBehavior

{

    #region IEndpointBehavior Members

 

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)

    {

        var cc = bindingParameters.Find<ClientCredentials>();

        if (cc == null)

        {

            cc = new ClientCredentials();

            cc.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;

            cc.ServiceCertificate.SetDefaultCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);

           //Use this client certificate to get a SAML token.

            cc.ClientCertificate.Certificate = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.CurrentUser, "cn=localhost");

            bindingParameters.Add(cc);

        }

    }

 

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)   {    }

 

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)    {    }

 

    public void Validate(ServiceEndpoint endpoint)    {    }

 

    #endregion

}

Comments [5] | | # 
 Friday, July 04, 2008
Friday, July 04, 2008 2:14:01 AM (GMT Standard Time, UTC+00:00) ( Federation/STS )

Pablo described here a way to configure federation over TCP. In his approach he gets a SAML token from STS and then uses that token to get a security context token which will be used to provide actual message security throughout the session.

As message security only works in a buffered mode, so his approach is not suitable for a TCP streaming scenario. To enable federation along with TCP streaming you have to use mixed mode security (TransportWithMessageCredential) over TCP.  Let’s consider following binding which uses mixed mode security.

      <netTcpBinding>

        <binding name="tcp" transferMode="Streamed">

          <security mode="TransportWithMessageCredential">

            <message clientCredentialType="IssuedToken"/>

            <transport clientCredentialType="Windows"></transport>

          </security>

        </binding>

      </netTcpBinding>

Now the trouble is that there is no way to configure STS settings in this binding configuration so your only choice is to mimic the above settings in a custom binding.

      <wsHttpBinding>

        <binding name="simpTransport">

          <security mode="Transport">

            <transport clientCredentialType="None"/>

          </security>

        </binding>

      </wsHttpBinding>

 

      <customBinding>

        <binding name="tcp">

          <security authenticationMode="SecureConversation">

            <secureConversationBootstrap authenticationMode="IssuedTokenOverTransport">

              <issuedTokenParameters>

                <issuer address="https://localhost:9000/STS" binding="wsHttpBinding" bindingConfiguration="simpTransport"/>

              </issuedTokenParameters>

            </secureConversationBootstrap>

          </security>

          <windowsStreamSecurity/>

          <tcpTransport transferMode="Streamed" />

        </binding>

      </customBinding>

Comments [0] | | #