Tools and articles

Some of our articles and tools that we use in everyday work

In our work, we pay great attention to education, and to explore new areas of development, which would increase the level of knowledge, not only our employees, but also all the people who are interested in developing in various spheres.

As the processing of this section will be filled with more and more new information and possible we will keep you informed of the new publications

Windows Identity Foundation — for ASP.NET MVC
In this article I would like to tell how to use Windows Identity Foundation in your ASP.NET MVC projects and to write your Identity Server, on WIF platform. Overall there is enough general information about this on the Internet, but it doesn’t really go into detail. Secondly, what is proposed by Microsoft now, using Visual Studio settings is not quite appropriate, even quite inappropriate for solutions which are more complex than a home page or business card web site. It’s also not so good when a mythical wizard does something with a solution and says that “more or less it should work”. As an example, we will create and set the most primitive client, which will authorize through the most primitive authorization server (Identity Server) functioning through WS-Federation WS-Federation protocol.

To determine in which cases it is a good idea to use your authorization server, we need to see how it works. Thus, we want to provide to client several services, for example several sites, for example with WCF services and for instance REST API. It would be quite inconvenient for user to pass authorization on each of our sites when moving on from one to the next. The simple idea is that when passing authorization on one of the services (resources), a certain Token is handed out. And subsequently another, or the same, service (resource) already trusts authorized user, on the basis of the client already having this very token etc.

Just for clarity of understanding, I will bring a comparison (unfortunately no link available). For example a person receives a passport, after certain checkup procedure, and subsequently this person has trust on the basis of this passport. In our comparison the passport is the actual client’s token.

It is obviously useless to hand out a passport if it will be checked only in one place.

Of course a token, same as a passport, has a life span, and of course a token can be updated based on the old one. And similarly to a passport a token can be different, perhaps as a request heading, or base64 string, for example JWT Token (JSON Web Token). In fact the actual token contains information about itself (time when it was last created, public certificate key etc.) also a claims list, containing information about the clinet. For describing a token, we will use SAML (Security Assertion Markup Language).

Another important notion is Claims. Claims are a part of our token and carry information about the client as a whole. In reality, it’s a dictionary consisting of Key/Value pair, in which Key-is namespace describing type of Value field, and the actual Value field-is a simple string. In .Net it’s presented as a typified list:

var claimsList = new List
      {
             	new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "Tester")
      };
There exists an entire row of registered namespaces, which are more than sufficient to describe client’s profile, from role list to avatar. If we wish we can create our own namespaces, the only thing to remember is that the actual Claim object needs to be serialized.

From here arise two main conclusions, firstly that to authorize a user on a site it’s unjustified to use Identity Server, and secondly that since we are going to pass on the token among various resources, we will require transport security first. And so let’s start, and let’s begin from setting transport, because if we won’t have trusted transport, nothing will function, and to proceed we will first require a certificate.

Creating a certificate


From about this moment, many developers will have questions about creating a certificate, HTTPS settings on the server etc. For work and debugging we will need the actual IIS set locally, a simple ASP.NET MVC application which will be our client site and a trusted certificate. We need a certificate given for some domain name, to buy it is not economically profitable, therefore we will make it ourselves.

For example, a domain name which we’ll be using for test purposes will be identity.com. At first, to create a certificate we will use makecert utility.
makecert -r -n "CN=*.identity.com" -cy authority -b 01/01/2000 -e 01/01/2099 -a sha1 -sr localMachine -sky Exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv identity.com.pvk identity.com.cer
As a result of execution we receive the following two files: identity.com.pvk and identity.com.cer. Everything is clear here, and there is enough information about makecert utility. The only moment which we would like to explore in more detail is CN on which we hand out the certificate. If to hand out the certificate simply on identity.com, then subsequently it will be inconvenient to locally model the situation with allocated resources, but using *, * significantly simplifies our task. *.identity.com. Using *, gives us the possibility to locally create random quantity of domains of "any name".identity.com.

Further, to check publisher’s certificate, let’s use cert2spc utility.
  cert2spc identity.com.cer identity.com.spc
And as a result, we will receive identity.com.spc, file which we will need for pvk2pfx. With the help of which we will generate pfx file.
pvk2pfx -pvk identity.com.pvk -spc identity.com.spc -pfx identity.com.pfx -pi "qwerty"
As a result we received identity.com.pfx file, containing private ключ, with qwerty password. It remains to register it in IIS and in the system.

HTTPS Settings


So that our IIS server begins to function with our certificate, firstly we need to import our pfx file into Trusted Root Certification Authorities zone through MMC equipment and execute Import in the actual IIS server, in Server Certificates section.

Now everything is ready for setting of our client site. For this let’s create a new site in IIS, with the name client.identity (actually regardless with which) most importantly that the App Pool of our site works under .Net 4.0 (that is if the site is compiled under .Net 4.0, 4.5). And indicate Physical path, to directory of our client site. Then we set our HTTPS in Binding section. After selecting https in type field, we need to select our generated certificate, and only after this Host name field becomes accessible for editing. If the certificate was generated with "*", then we can indicate practically any name of our site, importantly it needs to end with identity.com, ie the name of our test domain. Further we can change our bindings in Bindings section of our site. There remains only the last step, is to change hosts file, using path (c:\Windows\System32\drivers\etc\) and to add there a string with binding name of our site:
  127.0.0.1   client.identity.com
That’s it, we can check the function of local https, simply using the address: https://client.identity.com. As a result, we should see our web application, and in the address string that our certificate is trusted, ie no warnings from the browser.

If you download IdentityTrainingKitVS2010 from Microsoft site, it’s possible to simplify one’s life by executing SetupCertificates.cmd, for example using the path IdentityTrainingKitVS2010\Labs\MembershipAndFederation\Source\Setup\Scripts\SetupCertificates.cmd

This script does basically the same, but already for prepared host certificate from examples localhost.pfx (it has password xyz). In accordance, referring to site (for example Default Web Site), will work through localhost, and all applications which should work through https should be created not as Web Site, but as Web Application, under localhost site.

Settings of client application


Now we need to carry out the following settings of our client application. First, in project settings, let’s set our site’s address for filed Custom Web Server. This gives Visual Studio the possibility upon launch, to automatically do Attach to Process to w3wp.exe process (IIS site process).

Now we need to sort out references of our site and add two adjustments from GAC, System.IdentityModel.dll and System.IdentityModel.Services.dll. As well as remove what is unnecessary, which will hider us-it’s NUget packets DotNetOpenAuth, we will not need them, they will only hinder us, therefore it’s necessary to remove Microsoft.AspNet.WebPages.OAuth. If for any reason you don’t want to touch them, as an option-settings of registration in web.config.

And the last step, in settings of our client application is settings of the actual web.config. First, in system.web section set method authentication to none.

Then we register our section, for Identity Model in configSections:
Add and set these sections, first system.identityModel:

    
      
        
      
      
        
          
        
      
      
   

For a start, in audienceUris section, add address of our client site, then add record into trustedIssuers section, where thumbprint is meaning Thumbprint from our generated file identity.crt or another transport certificate, based on which our server will function. Do not use spaces. And the field “name” is actually the address of our future server, for example in our case https://server.identity.com + /issue/wsfed. It’s not necessary to use wsfed especially in case of our future server-it can be anything. Simply wsfed-is abbreviation of WS-Federation. Then we add system.identityModel.services section:

    
      
      
    

Here it is simple enough, iisuer-is our server from above section, and reply is address where subsequently server is to answer.

It remains to register modules, in system.webServer section.

      
      

Now it is possible to check the functioning of our client, it remains to try with View invoke any method or method controller marked by Authorize attribute.

After launching application (using F5) and attempts by user to invoke our method, we will see GET request on address of our future server:
https://server.identity.com/issue/wsfed?wa=wsignin1.0&wtrealm=https%3a%2f%2fclient.identity.com%2f&wctx=rm%3d0%26id%3dpassive%26ru%3d%252fAccount&wct=2014-09-23T13%3a36%3a21Z&wreply=https%3a%2f%2fclient.identity.com%2f
It’s a request for authorization, from client to server, using address https://server.identity.com/issue/wsfed.

Described above is enough for minimal setting of client application, working with WIF Identity Server, even if you use server of third party developers, the main thing is for server to support WS-Federation.

Creating server


Before starting to create Identity server, it’s necessary to mention STS (Security Token Service). Actually it’s a service, and it’s not important in which language or platform it is written. And our ASP.NET MVC Identity Server is basically UI. To create our STS, as we use .Net, it’s convenient to use instruments already available in the platform.

Our Identity Server, same as client, basically provides ASP.NET MVC application, for which HTTPS needs to be set, and, in our case, we will assign it binding https://server.identity.com, using the same, previously generated certificate.

Let’s create SignIn View for SignIn method of Account controller, and add the following record to web.config:

	

And let’s add into routes, record for controller method, which will be executed on appealing to path issue/wsfed.
routes.MapRoute("wsfederation",
                    "issue/wsfed",
                    new { controller = "WSFederation", action = "issue" });
Precisely using this path appeals our client <>/issue/wsfed. If we are controller, we mark by Authorize attribute the client application, on attempt to carry out entry into the system, will fall first onto SignIn method, of Account controller, which in its term will return View, with log in form of our server. Then user enters data, necessary for entry (for example log in password) and falls onto Issue method. Note that RequestString doesn’t change, but remains the same, with which appealed the client application. In order for our server to understand, what precisely client wants from it, let’s sort out request arguments:
        public ActionResult Issue()
        {
            WSFederationMessage message = WSFederationMessage.CreateFromUri(HttpContext.Request.Url);

            // Sign in
            var signinMessage = message as SignInRequestMessage;
            if (signinMessage != null)
            {
                return ProcessWSFederationSignIn(signinMessage);
            }

            // Sign out
            var signoutMessage = message as SignOutRequestMessage;
            if (signoutMessage != null)
            {
                return ProcessWSFederationSignOut(signoutMessage);
            }

            return View("Error");
        }
Accordingly WSFederationMessage.CreateFromUri method returns instance of inheritors of abstract class WSFederationMessage. Then we carry out actions either for entry into the system, or exit.

When carrying out entry into the system using WS-Federation protocol, execute static method:
FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest
This method, on the basis of received class instance SignInRequestMessage, and Claims list, will form a certain RequestSecurityToken, which in essence is our client’s Token, and will give it to GetScope method of our STS service. To create our STS service, inherit from abstract class SecurityTokenService:
  public class TokenService : SecurityTokenService
and overlap GetScope method:
protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
Precisely in this method will go ahead analysis or filling in of RequestSecurityToken that is, immediate actual formation or check of client’s token. I do not see the point in describing entire check, as it is simpler to go over the method with debug, as the method doesn’t contain anything trivial.

Essentially, described above is sufficient to receive a primitive Identity Server, through which client can authorize.

If it will be interesting to see how it all works, I “glued” a simplified client and server, on github. It is a simply a lighter version of https://github.com/thinktecture/Thinktecture.IdentityServer.v2, server, built for the given moment, simply for demonstration purposes and will not stand any criticisms.

Conclusion

What I wanted to receive as a result was a fully functioning Identity Server, into which all work with user profile is placed, ie log in, registration, social networks, review of their profile etc. Accordingly with relevant security level. But in fact in order to connect the actual server to developed resource, and each time not to waste time on authorization system. And of course it was desirable to integrate server’s functioning with WCF and REST services, with partitioning access to methods using client roles. But that remains just in plans.

Useful links

What is Identity Foundation: http://msdn.microsoft.com/ru-ru/library/ee748475.aspx
Sources of several Identity servers and useful libraries: https://github.com/thinktecture
A good report about Claims-based authorization: https://www.youtube.com/watch?v=WHSDIiwQlS8
More examples: http://claimsid.codeplex.com
And Codeproject: http://www.codeproject.com/Articles/504399/Understanding-Windows-Identity-Foundation-WIF

New comment:

News and Events

This report describes the basic principles of working with the MQ services, particularly RabbitMQ use C#
Legend:
  1. MQ Services — an overview of where the services are used and which one is best to choose?
  2. RabbitMQ — installation and configuration
  3. Push-messaging use RabbitMQ and .NET C#
  4. Integration with other platforms
  5. Alternatives and what to expect next?
More details...
This report describes how to run ASP.NET code on a virtual server for $ 5 per month, and why you should not do
Legend:
  1. Why choose ASP.NET
  2. Why save on the server, if it can be hosted in Azure?
  3. How to run a container locally and remotely
  4. Practical recommendations
More details...