zondag 25 maart 2012

Readonly collections with Entity Framework

If you want to use readonly collections inside Domain Objects (like I did here) and are using Entity Framework Code First you currently have a problem, because collections of type ReadOnlyCollection are not supported.

Luckily I've found a way to work around this.

Let's start with an object which has a  ReadOnlyCollection :

public class Phase
{
   public int Id { get; set; }
   public bool IsClosed { get; set; }

   private List<Task> _tasks;
   public  ReadOnlyCollection<Task> ReadOnlyTasks
   {
      get
      {
         return new ReadOnlyCollection<Task>(_tasks);
      }
   }
} 

The problem with the code above is that Entity Framework can't map to private fields and it can't fill a ReadOnlyCollection.
What we can do is create a custom List which behaves like a readonly collection. For starters this means that the Add method is disabled:

public class ReadOnlyList<T> : List<T>
{
   /// <summary>
   ///  Not supported, because it's not allowed to add
   ///  items to a readonly list
   /// </summary>
   public new void Add(T item)
   {
      throw new NotSupportedException();
   }
}

Now we can use this  ReadOnlyList in our Domain Object:

public class Phase
{
   public int Id { get; set; }
   public bool IsClosed { get; set; }

   public ReadOnlyList<Task> ReadOnlyTasks
   {
      get;
      private set;
   }
}  

One problem solved: Entity Framework is able to fill the ReadOnlyList we created.
But now the Add method isn't supported anymore, how can we fill this list ourself? We have to create another add method, but this time we make it internal:

public class ReadOnlyList<T> : List<T>
{
   /// <summary>
   ///  Not supported, because it's not allowed to add
   ///  items to a readonly list
   /// </summary>
   public new void Add(T item)
   {
      throw new NotSupportedException();
   }

   internal  void AddItem(T item)
   {
      base.Add(item);
   }
}

We can use the AddItem method like this:

public class Phase
{
   public int Id { get; set; }
   public bool IsClosed { get; set; }

   public ReadOnlyList<Task> ReadOnlyTasks
   {
      get;
      private set;
   }

   public void AddTask(Task task)
   {
      ReadOnlyTasks.AddItem(task);
   }
}  

So how do we use the Phase class after we wrote this code? For example an MVC controller can look like this:

public ActionResult Index() 
{
   var phase = PhaseRepository.GetById(1);
   phase.AddTask(new Task());
} 

What would happen if we call the Add method on the ReadOnlyTasks list, like this:

public ActionResult Index() 
{
   var phase = PhaseRepository.GetById(1);
   phase.ReadOnlyTasks.Add(new Task());
} 

The code above will throw an  NotSupportedException, just as we wrote. So it is indeed a readonly list. But it's not very nice that we can call the Add method, the code compiles without any problem, but at runtime it will fail. It would be much nicer if we can do something to the Add method so we can't call it. Unfortunately we can't make it private or internal, because the public Add method of the List we inherited will become available. But there's another solution: mark the method with the System.Obsolete parameter, like this:

public class ReadOnlyList<T> : List<T>
{
   /// <summary>
   ///  Not supported, because it's not allowed to add
   ///  items to a readonly list
   /// </summary>
   [Obsolete("Not supported, because it is not allowed to add items to a readonly list", true)]
   public new void Add(T item)
   {
      throw new NotSupportedException();
   }
   ...
}

Now, if we try to call the Add method from an MVC Controller, we see this:





This helps us a lot by not making the mistake of calling Add on the readonly list. And if still continue, and type something like this:

phase.Tasks.Add(new Task());

We will get an error at compile time, so our code will never run. We now can only add items to the readonly list by calling the AddTask method on the Phase class, exactly as we wanted.


Btw. this solution is not completely air tight, because we can still cast our Readonly list to a List and the Add method is back available again. But at least we have a pretty clean solution for Readonly lists with Entity Framework.

Domain Driven Development - Business Logic in Domain Objects


Introduction
One of the recurring questions in developing software in C# is where to put Business Logic. It's quite easy to scatter Business Rules throughout the system, in such a way that it will be very hard to maintain the code.


Let's take for example this Business Rule:
When a Phase is closed, no more Tasks can be added to it.


If we build a simple system these two objects can look like this in code:


public class Phase
{
   public int Id { get; set; }
   public bool IsClosed {  get ;  set ; }
   public List<Task> Tasks {  get ;  set ; }
}


public class Task
{
    public  string Name {  get  ;  set ; }
}


And we can interact with Phase and Task like this:


var phase = _phaseRepository.GetById(1);


if(!phase.IsClosed)
{
   phase.Tasks.Add(new Task());
}



What is the problem with this code?
The problem with the code above is that if in one place we forget to check if the Phase is closed, we can add Tasks to a closed Phase. So, mistakes are quite easy to make in this case.
Another problem is that we have to copy the check for IsClosed every time we want to add Tasks to a Phase in another part of the system.
And a third problem is that whenever we add another condition to the Business Rule, we have to go through all code where we Add Tasks and add code for the new condition.


What is the solution?
It's better to move this Business Rule to the Phase object, like this:


public class Phase
{
   public int Id { get; set; }
   public bool IsClosed { get; set; }
   public List <Task> Tasks { get; set; }


   public void AddTask(Task task)
   {
      if(IsClosed)
      {
         throw new Exception("Can't add tasks to closed Phase.");
      }
      Tasks.Add( task );
   }
}

Now we can simply use the code above like this:

var phase = PhaseRepository.GetById(1);
phase.AddTask(new Task());




This looks a lot better. And if we add another property to the Phase which has to be checked when we add a Task, we only have to change the Phase object, and not the code in the controller.


We're not there yet
Although we now have a nice AddTask method, we can still easily get around it, because the List<Task> Tasks on Phase is public and has an Add method. So we can do this:


var phase = PhaseRepository.GetById(1);
phase.AddTask(new Task());
phase.IsClosed = true;
phase.Tasks.Add(new Task()); 


We can solve this by making the Tasks list readonly:


public class Phase
{
   public int Id { get; set; }
   public bool IsClosed { get; set; }

   private List<Task> _tasks;
   public  ReadOnlyCollection<Task> ReadOnlytasks
   {
      get
      {
         return new ReadOnlyCollection<Subforum>(_tasks);
      }
   }
}


And you will see that the Add methods isn't supported anymore. So everytime we want to add a Task to a Phase we have to use the AddTask method.


var phase = PhaseRepository.GetById(1);
phase.AddTask(new Task());
phase.Tasks.Add(new Task()); 


Entity Framework
So what if we use Entity Framework, does this solution work? No it doesn't work completely, because Entity Framework doesn't support ReadOnlyCollection<T>. But I have a solution for that, as you can read in the blog post I wrote:


Readonly collections with Entity Framework

zaterdag 17 maart 2012

Created a website to try Azure out

I've created www.BbsFactory.com which basically is a website with which you can create a hosted forum. So in other words it's a Forum as a Service.


This site helps me to try out things on Windows Azure, which works a lot better then trying yet another Hello World sample.

donderdag 9 februari 2012

Azure webrole federated by ACS

Problem
If you deploy a Web Role secured with ACS, and you have two or more instances of your Web Role, you probably have seen this error message:


Key not valid for use in specified state


The problem is that the cookie that is created if you log in with ACS, is encrypted with the machine key by default. If the cookie is created by one of the instances, the cookie can not be read by the other instances because their machine key is different.


Solution
There is a solution to this: encrypt the cookie using a certificate that is known to all instances.


How to
I'll show you how a self-signed certificate can be used to encrypt the ACS cookie.


Create a certificate
First, on your dev machine open IIS and create a self-signed certificate. This certificate can be used on your Azure development environment as well as on the staging and production environment.


Give rights on certificate
To be able to use it on your development machine do the following:
Go to MMC to view the certificates in the Personal store of Local Computer. Right click on the created certificate and choose [All Tasks] [Manage Private Keys...]. Add the username 'Network Service' with read rights.
Network Service is the account under which the Azure simulation environment is executing. It now has rights to read the self-signed certificate.


Add certificate to config
Next we have to use this certificate in our Web Role. Open the ServiceDefinition.csdef file. Add the following code under the WebRole node:



<Certificates>
   <Certificate name="CookieEncryptionCertificate"
                storeLocation="LocalMachine"
                storeName="My" />
</Certificates>




Now your definition file should look something like this:



<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="AutofacTestAzure"
                   xmlns="http://schemas.micros[...]">
   <WebRole  name="[name]" vmsize="Small">
      <Certificates>
         <Certificate name="CookieEncryptionCertificate"
                      storeLocation="LocalMachine"
                      storeName="My" />
      </Certificates>
...
   </ WebRole >
< ServiceDefinition >




Add the following text to all cscfg-files where you want to use the certificate:



<Certificates>
   <Certificate name="Cookie" thumbprint="[thumbprint]"  thumbprintAlgorith="sha1" />
</Certificates >

You can find the [thumbprint] value if you view the Details of the certificate in IIS. Make sure you remove the invisble space at the start of the thumbprint value, after you paste it into the xml.
Example thumbprint value "5a 0a e8 80 f4 ..."
At this position "(here)5a 0a e8 80 f4 ..." you'll notice an invisible space. Make sure you remove that.

Use certificate in code
We can now make some changes in code, so the certificate will be used to encrypt the cookie.
Add this code to the Application_Start event in the global.asax:

FederatedAuthentication.ServiceConfigurationCreated += FedAuthServiceConfigCreated;

So it will look like this:


protected void Application_Start()
{
   FederatedAuthentication.ServiceConfigurationCreated +=
      FedAuthServiceConfigCreated;
   ...
}

Add this method to the global.asax.cs:

private void FedAuthServiceConfigCreated(
   object sender, ServiceConfigurationCreatedEventArgs e)
{
   // Use the <serviceCertificate> to protect the cookies
   // that are sent to the client.
   var readonlyCookietransformList = new CookieTransform[]
   {
       new DeflateCookieTransform(),
       new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate)
   }.ToList().AsReadOnly();


   var sessionSecurityTokenHandler =
       new SessionSecurityTokenHandler(readonlyCookietransformList);


   e.ServiceConfiguration.SecurityTokenHandlers
      .AddOrReplace(sessionSecurityTokenHandler);
}



If you press F5 now, you'll see everything works locally.


Time to get things working in the cloud
There's only one thing we have to do to get this working in the cloud, and that's to upload the certificate to our Hosted Service.
First, go to the created certificate in IIS and export it to a .pfx file. Next go to the management portal and import the certificate to the Certificates of the Hosted Service.




That's all. You can upload your Web Role to Azure and everything works.

donderdag 12 januari 2012

Secure WCF Service with ADFS


Introduction
This article describes how to secure a WCF Service by ADFS.


ADFS
Create a Relying Party in ADFS. Use these settings:

Display name = Name of the service
Profile = AD FS 2.0 Profile
Certificate = encryption certificate
Configure URL = uncheck both options
Identifiers = complete url of the service, for example https://www.hostname.com/service1.svc
Auth = Permit all users


Certificates
These are the needed certificates:

SSL certificate for the WCF service in IIS
  • Create this with CertSrv. Make sure the CN Name is the same as the hostname used for the WCF Service in IIS.
  • Import without private key into Trusted People store

Encryption certificate for the relying party in ADFS
  • Import with private key into Personal store
  • Give rights to IIS_IUSRS

Credentials certificate for the client
  • Import with private key into Personal Store
  • Give rights to the windows account the application is running under, or app pool the website is running under



Console Application code

string userCertificateThumbprint =  "[thumbprint of Credentials certificate for the client]";

var channelFactory =
      new ChannelFactory<ISync>("ServiceReference1.ISync");


// Set certificate for user
channelFactory.Credentials.ClientCertificate.SetCertificate(
   StoreLocation.LocalMachine,
   StoreName.My,
   X509FindType.FindByThumbprint,
   userCertificateThumbprint);


var wcfClient = channelFactory.CreateChannel();


var res = wcfClient.Foo();


Active Directory
Create a user in Active Directory.
Login to CertSrv and with the created user, and create a certificate. It will be automatically set in AD.
The created certificate will be stored in the Personal store of the Current User. It should be imported into the Personal store of Local Computer this way:

  • Open MMC
  • Go to the Personal Store of Current User
  • Export the created certificate including it's private key
  • Go to the Personal Store of Local Computer
  • Import the certificate
  • Make a note of the thumbprint, it should be put into the Console Application config later.







WCF Service configuration
Add this code to the app.config of the WCF Service:




<configSections>
  <section
  name="microsoft.identityModel"
  type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>


<system.serviceModel>
<services>
  <service
    name="[Name of the service]"
    behaviorConfiguration="federationBehavior">


    <endpoint
      address=""
      binding="customBinding"
      contract="[Interface implemented by the WCF Service]"
       <!-- example: Wcf.IService1 -->
       
            bindingConfiguration="WifActiveFedBinding" />


    <endpoint
      address="mex"
      binding="mexHttpsBinding"
      contract="IMetadataExchange" />
  </service>
</services>


<behaviors>
  <serviceBehaviors>
    <behavior name="federationBehavior">
      <federatedServiceHostConfiguration />
      <serviceMetadata httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />


      <serviceCredentials>
        <!-- Encryption certificate for the relying party in ADFS -->
        <serviceCertificate
          findValue="[thumbprint]"
          storeLocation="LocalMachine"
          storeName="My"
          x509FindType="FindByThumbprint" />
       </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>


<extensions>
  <behaviorExtensions>
    <add
      name="federatedServiceHostConfiguration"
      type="Microsoft.IdentityModel.Configuration.ConfigureServiceHostBehaviorExtensionElement, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </behaviorExtensions>
</extensions>


<bindings>
<customBinding>
<binding name="WifActiveFedBinding">


<security
authenticationMode="SecureConversation"
messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSecurityContextCancellation="false">


<secureConversationBootstrap
authenticationMode="IssuedTokenOverTransport"
messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10">


<issuedTokenParameters>
<additionalRequestParameters>
<AppliesTo>
<EndpointReference>
<!-- Base address of the WCF Service. -->
<!-- Use a domain name, don't use an ip address. -->
<!-- Domain name must be same as defined in certificate -->
<Address>https://[DomainName]/</Address>
</EndpointReference>
</AppliesTo>
</additionalRequestParameters>
</issuedTokenParameters>


</secureConversationBootstrap>
</security>


<httpsTransport />


</binding>
</customBinding>
</bindings>
</system.serviceModel>




<microsoft.identityModel>
<service>
<audienceUris>
<!-- All endpoints that need to be secured. -->
<add value="https://[DomainName]/[ServicePath]" />
   <!-- example: https://www.mywcfservice.com/wcf.service1.svc -->
</audienceUris>


<issuerNameRegistry
type="Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">


<trustedIssuers>
<!--Signing certificaat of ADFS -->
<add
thumbprint="thumbprint of signing certificaat of ADFS"
name="http://[adfs server]/adfs/services/trust" />
</trustedIssuers>
</issuerNameRegistry>
</service>
</microsoft.identityModel>










Console Application - app.config


<configSections>
   <section       name="microsoft.identityModel"
      type="Microsoft.IdentityModel.Configuration.MicrosoftIdentityModelSection, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>




<system.serviceModel>
   <bindings>
      <customBinding>
         <binding name="WifActiveFedClientBinding">
        <security
authenticationMode="SecureConversation"
messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10">

            <secureConversationBootstrap
authenticationMode="IssuedTokenOverTransport"
messageSecurityVersion="WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10">

<issuedTokenParameters keyType="SymmetricKey" tokenType="">

                <additionalRequestParameters>
                  <trust:SecondaryParameters
                    xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
                    <trust:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey</trust:KeyType>
                    <AppliesTo xmlns="http://schemas.xmlsoap.org/ws/2004/09/policy">
                      <EndpointReference xmlns="http://www.w3.org/2005/08/addressing">
                        
<Address>http://mandatorybutdoesntmatter/</Address>
                      </EndpointReference>
                    </AppliesTo>
                  </trust:SecondaryParameters>
                </additionalRequestParameters>

                <issuer
address = "https://[adfs hostname]/adfs/services/trust/13/certificatemixed"
binding="ws2007HttpBinding"
bindingConfiguration="certificateTrust" />

              </issuedTokenParameters>


            </secureConversationBootstrap>
          </security>


          <httpsTransport/>
 
        </binding>
      </customBinding>
 
<ws2007HttpBinding>
<binding name="certificateTrust" >
          <security mode="TransportWithMessageCredential">
            <message
clientCredentialType="Certificate"  establishSecurityContext="false" />
          </security>
        </binding>
      </ws2007HttpBinding>
    </bindings>




    <client>
      <endpoint
         address="https://[DomainName]/[ServicePath]"
         <!-- example: https://www.mywcfservice/wcf.service1.svc   -->
         binding="customBinding"
         bindingConfiguration="WifActiveFedClientBinding"
         contract="ServiceReference1.ISync"
         name="ServiceReference1.ISync">
     <identity>
          <certificateReference
            storeName="My"
            storeLocation="LocalMachine"
            x509FindType="FindByThumbprint"
            findValue="[thumbprint of SSL certificate for the WCF service in IIS]" />
        </identity>
      </endpoint> 
    </client>


  </system.serviceModel>




</configuration>

vrijdag 18 november 2011

Turn off Home Realm Discovery in ADFS 2.0

Introduction
When you've added another Claims Provider Trust to ADFS, next to ADFS, you'll see the HomeRealmDiscovery page when you try to logon. This page looks like this:






Problem
Most users don't know what to select here. So you wouldn't want them to see this page.


Solution
You can add a setting to your application web.config which tells adfs to use a specific Claims Provider. This setting is called homeRealm. The value can be found in Adfs Management tool. 



<federatedAuthentication>
   <wsFederation
      passiveRedirectEnabled="true"
      issuer="[adfs]"
      realm="[website url]"
      requireHttps="true"
      homeRealm="[Claims provider identifier]" />
   ...
</federatedAuthentication>