Overview: Using Claims-based Access on Windows Azure

February 6, 2011 2 comments

Introduction

On this blog, I would like to talk about a technology which will simplify user access for developers by allowing building claims-aware application: Windows Identity Foundation (WIF). The goal is to improve developer productivity, enhance application security, and enable interoperability. For most of us claims-aware authentication is nothing new, the new part I’m writing about is how to implement it in Windows Azure environment. If you already developed some solutions with WIF and also know what claims-based identity means, you can save some reading and jump directly to the Windows Azure section.

Background

Authorization and authentication is a very important aspect of any software solution. But somehow many software solutions are not good enough designed to protect private or important data against attackers.

Many applications have their own user identity store developed into their business layer, where it has to be maintained and supported along with the application by developers. I’m not saying that every solution is like this on the world, there are many examples of centralized authorization and authentication solutions, but as we are entering another era, where we are moving our solutions to Windows Azure, it is becoming clear to us that our security solutions does not provide the required scalability and extensibility.

Claims-based Solution

Thanks to Windows Identity Foundation (WIF), we have the option to stop writing our custom identity plumbing and user identity databases for every application using .Net Framework. So, what is claims-based identity? I’ll try to explain it very short; the following diagram shows a simple and classic authentication implementation:

Diagram – 1

The client enters user name and password (1) to get access to the secure area. The data is passed to the security layer (2), where the credentials are validated against a user identity store (3). Then the result is most probably returned in form of some user claims (4) and passed to the application (5). The term “Claims” is used here in order to express that the data returned from the identity store has also more than just user properties. A claim can be a user’s email address, department etc. But claims are a little more than just user properties; claims include trust information about the provider too. At the end the client may receive access to the secure data (6).

Windows Identity Foundation

There is nothing wrong with this picture until you want to implement a different security, enhance your security or add one more application to your system. The problem is that you have to modify your code based about identity and security. Claims-based identity allows you to decouple this logic from the heart of your application and give the responsibility to another entity. That entity is the Identity Provider, as seen below:

Diagram – 2

The client starts with requesting the token requirements from the application (1), receives them (2) and passes them to the Identity Provider’s Security Token Service (STS) along with the user name and password (3). The STS validates the user information against the user identity store (4) and receives the token answers in form of claims (5). Then it passes the token along with the claims and a public key back to the client (6). The client forwards the token to the application. The application uses (8) WIF to resolve (9) the token (Canonicalization, Signature checking, Decryption, Check for expiration, Check for duplication etc) and maybe receives the claims it requires out of the token (10) if the token is valid. At the end the client may receive access to the secure data (10).

At the first look it looks like we are introducing a lot of steps (from 6 to 11), but when you think about the simplicity about the code you have to write to authenticate a user in your application using WIF saves a lot of trouble. For example, the only code I have to write to get a claim looks like this:


protected void Page_Load(object sender, EventArgs e)

{

    IClaimsIdentity claimsIdentity = ((IClaimsPrincipal)(Thread.CurrentPrincipal)).Identities[0];

    String userEmail =

        (from c in claimsIdentity.Claims

        where c.ClaimType == System.IdentityModel.Claims.ClaimTypes.Email

        select c.Value).FirstOrDefault();

}

In this code, we are accessing the instance of our claims identity and querying the claims for the email address, which is a claim from a token generated by the STS. The rest is only application configuration. For example, in a very simple implementation we could only setup some pages to be seen by a certain role and make the following configuration:

<location path=”SecretPage.aspx”>

<system.web>

<authorization>

<allow roles=”Manager”/>

<deny users=”*”/>

</authorization>

</system.web>

</location> 

Please check out the SDK and Toolkit links below, you will really enjoy the practicality of this framework.

Practicality is not the only advantage; it is also powerful when we want to implement different authentication technologies. For example switching to use active directory will not require any code changes on your application as well as on the communication to your application as seen below:

Diagram – 3

With said that, I would like to introduce you to the other parts of the Microsoft’s Identity and Access Platform software family: Active Directory Federation Services (ADFS) 2.0 and Windows CardSpace 2.0. You can get more information about these technologies on
http://msdn.microsoft.com/en-us/security/aa570351.aspx. I’ll not get into the details of ADFS and CardSpace because it is outside our current scope, but those are nice technologies which you may use for your custom solution.

Customization

You can also develop your own custom STS with the help of the Windows Identity Foundation SDK. Creating a custom STS is as simple as right clicking your project, selecting “Add STS reference…” and following the wizard to create a new STS project. For more information you can download WIF and WIF SDK from these links:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=eb9c345f-e830-40b8-a5fe-ae7a864c4d76&displaylang=en

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c148b2df-c7af-46bb-9162-2c9422208504&displaylang=en.

And please do not forget the Toolkit from here
http://www.microsoft.com/downloads/en/details.aspx?displaylang=en&FamilyID=c3e315fa-94e2-4028-99cb-904369f177c0, which provides all possible code examples you would need. Just a note: Please start first by setting up your environment as described in the Setup.docx in the Assets folder of the toolkit. I’m one of those who read the manual last, you can save the time until that point:)

Windows Azure

Now, how all this will help us on Windows Azure platform?

There are many scenarios you can start using Windows Azure platform as a part of your solution. One of them is to place your application to the cloud and keep your STS on-premise. In this way you can still take advantage of local identities for authenticating your users and take advantage of Windows Azure features like load balancing, scalability etc. The following diagram shows this example:

Diagram – 4

The logic is very similar to the previous once; the client connects to the application (6) only after sending the application (in this case a ASP.Net web application on a ASP.Net web role) a token (5) which was gathered from the identity provider (4) based on the requirements defined by the application (2). I did not draw the details of the identity provider and application because if can vary as I described in the claims-based identity scenarios. Please notice that the WIF is still used in the application on the Windows Azure. But, WIF is not in the Windows Azure GAC which is visible to the Windows Azure applications. Therefore I wanted to point it out that it is manually referenced.

One of the important details is to know that the application hosted in Windows Azure can have a different URI because of development, testing and production environments. Therefore the application’s URI should be dynamically embedded into the token for reply. As a result, the STS has to also be modified to validate the reply URI.

Another detail is to establish a trust relationship between the ASP.Net Web Role and the STS. That is simply done with the wizard which shows up when you right-click on your application project and select “Add STS reference…”.

One another key scenario is to also to delegate the Identity providing part to Windows Azure. That is by using the Windows Azure AppFabric Access Control technology instead of our STS.

The usage of AppFabric Access Control is shown in the following diagram:

Diagram – 5

As you can see, the claims-based workflow is not changed much; I only simplified the communication (1) just for clarity purposes. The SWT stands for Simple Web Token.

You can get more details about this scenario from the WIF toolkit labs at
http://msdn.microsoft.com/en-us/wazplatformtrainingcourse_introtoacslab2010_topic2.aspx .

Conclusion

Using claims-based access solutions simplifies a project in many aspects like maintenance, security, extensibility etc. Having this technology applied to the cloud, expands our endless solutions space in another dimension. I only scratched the surface of this nice technology, please go ahead and check out the resources I pointed in this post. I hope you will enjoy it as much I did.

Aiming a different prosperity: Ecosia

January 30, 2011 1 comment

I came across this amazing corporation where ecological and social goal is written in their constitution. Unlike some other corporations, their goal is not about relentless and mindless pursuit of profit growth: Ecosia internet search engine donates %80 of his income to support WWF’s work in the Amazon to save the rainforest.
Please check it out www.ecosia.com

Categories: Beyond Tags:

Are you really addressing the problem?

January 30, 2011 1 comment

Introduction

Some time ago I came across a software architect who had the “my way or the highway” attitude on providing solutions. I had a very interesting conversation with him about IoC containers; here is a part of the conversation:

him : What are you using currently as the IoC container.
me : I wrote one based on our companies requirements.
him : No, you can not do that, you have to use Microsoft’s Enterprise Library!

This is totally opposite thinking approach to mine; so far I read, learned and experienced about software architecting is that you can not hold on a solution and try to stick it into every problem. First the famous saying “If you only know how to use a hammer, every problem is a nail” comes to my mind, second I’m asking what does he know about my problem domain? Does he know what my non-functional requirements are? Does he know what kind of company, team, time or project I’m talking about? Certainly not, he is just thinking solution first!

After thinking about this situation, I figured out that a lot of people are thinking alike: certain things HAS to be done in a certain way with a certain technology. I believe that this mindset is the biggest roadblock of becoming a good architect who delivers projects successfully. Therefore I decided to write this post to explain what are some basic steps you have to follow which will help you to become a better software architect or better said deliver projects successfully.

The key term here is “successful project”; a project is ment to be successful when it complies with the requirements. Said that, the most important aspect of a solution is to be compliance with the requirements.

Requirements

Requirements describe the problem domain. Depending to the project and the chosen methodologies, the requirement can be acquired in advance or can be adjusted while the project is in progress. Requirements are provided by the stakeholders usually in a form of a document named System Requirements Document, which could be directly a subject matter expert or a business analyst which is a domain expert.

Note: This document should not be confused with a project vision document. There are different deliverables in software development projects, for more information you can visit Microsoft Solution Framework resourcese like this link http://msdn.microsoft.com/en-us/library/dd286619.aspx). Actually, some projects are not started with a requirements document, but that does not mean that we can just omit the requirement; an architect needs to work with the stakeholders. It is also well-known that there is nothing temporary than permanent requirements in a project:) but this fact should also not be a reason to act like a stranger to the stakeholders.

The problem domain contains a horizontal and a vertical axis. Mostly, the stakeholders are responsible of the vertical axis which contains their specific industry knowledge. The horizontal axis defines domains which apply to all industries, like SSL, WCF etc. But I’ve never seen a document defining the domains, we always define requirements and provide solution in domains.

Requirements are divided into two main categories named functional and non-functional requirements. Functional requirement defines what a system is supposed to accomplish, like input, output and behavior. Functional requirements are usually implemented in code; it helps to design a system and architect the application. But, I saw a lot of architects thinking that code is the only artifact that matters in a software development project. This mindset is known to be a developer attitude in solution space and architects should avoid it.

Note: This mindset is really hard to change especially if you got promoted from a developer to an architect. Unfortunately, that is the way it is happening today: once you develop software for 10 years, you become an architect. This makes us believe that architect is the next title. But in realty, software architecture is a totally different career path and just a small part is a bout coding. I’m strongly suggesting to read Microsoft Architecture Journal 15 ( http://msdn.microsoft.com/en-us/architecture/cc505966 ) for those who are architect. A good architect understands that software solutions consist of more than functional requirements.

On the other hand, non-functional requirements define the operation of the system, which gives the project its unique flavor or better said quality. Security, performance, scalability, testability, usability, price, privacy, extensibility, support, deployment etc. qualities are just couple of them.

It is very possible that functionally two same products can be totally different because they are relative to non-functional requirements. e.g. a web site which will support 10 users for his entire life would be different from a web site which will support million users.

Therefore, I believe that problem first thinking approach will save your project a lot of time and money; as much as you listen to your stakeholders, as much as you study them and understand the problem, as closer solution to their needs you will provide.

I saw the humorous drawing below, which is based on project management, but has some architecting flavor in it. I don’t know who should the credits go for capturing this real world problem, but this picture is thousand words worth.

Solution

Solution should always come after the requirement is understood well. But, that does not mean that the whole project requirement has to be understood well. You can grab one, all or group of related requirements, understand them, and work on the solution in that context.

That’s why I look at the solution as something relative to the requirement. And because every project is unique by time, company, team, budget, culture and requirements, it is impossible to have two the same solution. Therefore, even having finished a project successfully will never guarantee you the success for other one.

Every architects provides his solution in the way they know the best. The only common ground is the industry proven patterns and best practices; those are an architects tool belt. An architect has to look at the requirements and investigate a tool for the problem. I’m not saying choosing a tool, because there are and will always be more tools than you know, no matter how much you learn. I’m suggesting to start every requirement by accepting that we don’t know anything about it. The worst thing we can lose is to read a subject the second time. But what we gain is to extend the solution space outside our knowledge.

Perhaps there is no exact formula of how to architect a good solution; there is common logic which every human brain can think about, there is experience which everybody holds a piece and there are diverse blogs like this to increase communal innovations. Please visit also the Microsoft Architecture Center (http://msdn.microsoft.com/en-us/architecture/cc511514) which is a great resource for those who are on architect path. And please don’t forget that every solution is relative to requirements, time and place.

Conclusion

Going back to top of this post: I would expect from a good architect to reply to me as: “Interesting choice; what were the requirements to make this choice?”.

Under the hood of anonymous methods in C#

January 24, 2011 Leave a comment

Introduction

On this post I’ll help you to make better decisions on using C# anonymous methods. We all have our favorite or known ways to program certain solutions. But I believe that providing the right solution for the problem requires us to free our mind of all biases and think in the context of the problem. Every feature, including GOTO, has a place in this endless solution universe, therefore I’m not telling what not to use, I’m just showing under the hood, so you can make your own decision based on your unique solution.

Background

There are situations anonymous methods are really useful; especially if you have a small operation you want to do inline. Another point is that you loose on Readability and Testability; two important qualities of enterprise software. In smaller teams or developer owned projects, these qualities are sometimes omitted. (Nothing bad with that; as I said: there is a place for every feature). In bigger teams, especially if you have to review or continue another programmer’s code, it is really hard to read a line with complex inline code. I faced this problem many times on code review and code ownership changes.

So, let me show you what is going on under the hood, and you can make your own decision:

class Anonymous
{
	public void Method()
	{
		bool test = true;
		Action a = ()=> test = false;
	}
}

Figure – 1

In the example I used the anonymous method on an Action to simplify the disassembled IL code. The code looks very straightforward and simple to write; there is only one delegate which captures the boolean variable test and sets the value to false.

I kept the code simple to show the structural changes. There is even no call to the method; structurally it does not have any affect. What happens to the structure in the background after you compile, is shown in the disassemled MSIL code below (Collapsed IL code by purpose;to point to the structure):

.class private auto ansi beforefieldinit Anonymous
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }

    .method public hidebysig instance void Method() cil managed
    {
    }

    .class auto ansi sealed nested private beforefieldinit <>c__DisplayClass1
        extends [mscorlib]System.Object
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
        .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
        {
        }

        .method public hidebysig instance void b__0() cil managed
        {
        }

        .field public bool test

    }
}

Figure – 2

As you can see, a private sealed nested class named c_DisplayClass1 is created with one method named b__0 for our anonymous method. In the collapsed code our original Method method is modified in a way to create a new instance of c_DisplayClass1 to call the b__0 method. For those who are new to IL, I manually assembled it into C# code below:

class ILAssembled
{
	public void Method()
	{
		nested nt = new nested();
		nt.test = true;
	}

	private sealed class nested
	{
		public bool test;

		public void MethodNested()
		{
			test = false;
		}
	}
}

Figure – 3

The compiled IL code of the C# code above is exactly the same (excep some not important small changes). It is important to know that this IL result is for the code above. In fact, if I would move the local variable test to an instance variable, a method would be created instead of a nested class. Therefore, it is always safer to take a look at the disassembled IL code. My favorite tool is red Gate’s .Net Reflector, which can disassemble into many languages. Another big advantage of looking into the post compiled code is to study .Net Framework namespaces and learn good practices.

Let’s go back to our code. It does not mean that you could write the code in Figure-3 instead of in Figure-1 and save some compile time:). The point is that the magic is in the compiler in exchange of testability, readability and maybe some performance because you end up with a nested class instead of a method.

Instead, if I would write the code below, I would gain all the qualities I was looking for my unique solution:

public void Method()
{
	bool test = true;
	MyAction(test);
}
private void MyAction(bool test)
{
	test = false;
}

Figure – 4

As you can see, I created a method named MyAction to implement the functionality. Now I can create a unit test to test the MyAction and my colleagues can also understand the code at first look. It is really important to understand the code at first look if you are reviewing tens of classes; encrypting variable and method names, over using implicit type var and over using anonymous methods double or triple the review time.

For clarity I also provided below the disassembled IL code structure of Figure 4.(Collapsed IL code by purpose;to point to the structure):

.class private auto ansi beforefieldinit NonAnonymous
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
    }

    .method public hidebysig instance void Method() cil managed
    {
    }

    .method private hidebysig instance void MyAction(bool test) cil managed
    {
    }

}

Figure – 5

As you can see, there is no nested class declared to run the anonymous method.

Conclusion

I believe knowing what you are using is the key of making the right decision for you unique solution.