Monday, March 4, 2013

Websocket Demo

Here is a small sample to illustrate interacting with a websocket service using javascript.  I found the running echo service online at websocket.org.  The functionality of this service is that you send it a message and it sends the data back to you using the websocket events.   This sample code just spins off a few calls to the service (using milliseconds as differentiation) and writes the responses out to the document.  It is pretty straight forward, but does give you a working example.

The javascript:
   var wsUri = "wss://echo.websocket.org/";  
   var output;  
   function init() {  
     output = document.getElementById("output");  
     testWebSocket();  
   }  
   function testWebSocket() {  
     websocket = new WebSocket(wsUri);  
     websocket.onopen = function (evt) { onOpen(evt) };  
     websocket.onclose = function (evt) { onClose(evt) };  
     websocket.onmessage = function (evt) { onMessage(evt) };  
     websocket.onerror = function (evt) { onError(evt) };  
   }  
   function onOpen(evt) {  
     writeToScreen("CONNECTED");  
     var text = new Date();  
     doSend(text.getMonth() + 1 + '-' + text.getDate() + '-' + text.getFullYear() + ' at ' + text.getMilliseconds());  
   }  
   function onClose(evt) {  
     writeToScreen("DISCONNECTED");  
   }  
   function onMessage(evt) {  
     writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>');  
     setTimeout(onOpen(), 1250);  
   }  
   function onError(evt) {  
     writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);  
   }  
   function doSend(message) {  
     writeToScreen("SENT: " + message);  
     websocket.send(message);  
   }  
   function writeToScreen(message) {  
     var pre = document.createElement("p");  
     pre.style.wordWrap = "break-word";  
     pre.innerHTML = message;  
     output.appendChild(pre);  
     if (output.children.length > 20) {  
       websocket.close();  
     }  
   }  
   window.addEventListener("load", init, false);  
The page:
 <h2>WebSocket Test</h2>  
 <div id="output"></div>    

Thursday, February 28, 2013

Using MVC style controllers in ASP.NET WebForms with AJAX

I have been working on a project that is based in ASP.NET web forms recently with the knowledge that a near-future generation of this software will be created using MVC.  Always trying to find a way to share code and create leverage with solid SOA design, I decided to drive the ASP.NET application from controllers interacting with services.  By doing this, I am am assuring that not only the service layers are portable to other platforms, but that the controllers can be reused as well.  This gives us another layer of code reuse and a mechanism to limit the testing requirements on the future application.  The first step is to integrate the MVC references into your ASP application.  In order to do this, you must add the references to your project and include them in your web.config as follows.


Next, we have to make sure that our routes are created using the MVC 'magic'.  This is accomplished with a global.asax file executing the .net map paths functionality.  This is done via a single method call at the start of the application as illustrated below.
Code:
public class Global : HttpApplication
{
    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new {id = UrlParameter.Optional}
         );
    }
}

At this point, we are able to add controllers to interact with our data. The controller classes must be inherited from the Controller object. Once this class is stubbed in, you are able to simply frame in your methods to interact with the data as needed. Here is an example of a controller class.
Code:
public class TaskController : Controller    
{

    /// <summary>
    /// Completes the task.
    /// </summary>
    /// <param name="taskId">The task id.</param>
    /// <returns></returns>
    public ActionResult CompleteTask(int taskId)
    {
      
        try
        {
            MyTask data = ***service call to complete task and return updated data
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("");
        }
    }

    /// <summary>
    /// Get a list of tasks.
    /// </summary>
    /// <returns></returns>
    public ActionResult TaskList()
    {
       
        try
        {   
            List<MyTask> tasks = *** Service call to get task list.

            return Json(tasks, JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            return Json("");
        }
    }
}

The last step is to simply consume these controllers via AJAX calls in your client.
Code:
function loadTasks() {
    
    $.mobile.showPageLoadingMsg();
    var request = $.ajax({
        url: "/Task/TaskList",
        type: "POST",
        data: {},
        context: this
    });

    request.done(downloadDone).fail(downloadFailed).error(downloadError);
}

function downloadDone(responseData) {

    $.each(responseData, function (i, obj) {
         // do something with each task from the list by using obj.* to reference values.

    $.mobile.hidePageLoadingMsg();

}
function downloadFailed() {
    alert("Could not retrieve task data at this time.");
    $.mobile.hidePageLoadingMsg();
}

function downloadError(error) {
    $.mobile.hidePageLoadingMsg();
    console.log(error);
}

At this point, I can add controllers that represent my service interaction layer, and then simply reuse them when the application is migrated to MVC. This gives us the ability to separate the actual presentation layer from its interaction with the services and target that logic for reuse.

Friday, February 15, 2013

Azure Media Services

Microsoft has added more offerings to the already large catalog of Azure services.  Recently, they announced the launch of Azure Media Services which allows you to upload, encode and deliver streaming media content to a vast array of consuming devices.  Historically, we have had to partner with other vendors to provide the streaming media while leveraging Azure services to deliver our applications.  With this offering, it seems that you could simply partner with Microsoft and allow Azure to fulfill all of the needs you may have to deliver your assets to virtually any device.  While this offering is fairly new, I have gathered the following information.

Answering the Common Questions


1. Protection.  One of the first items people always bring up when building a streaming solution is the protection of assets.  Azure allows you to store and deliver content in a secure fashion by leveraging either Microsoft PlayReady DRM or Apple AES.  

2. User experience.  We are all concerned about ensuring that our content is seen in the best light possible at all times.  Azure Media Services offers the ability to not only encode your media into a large range of standard codecs and adaptive bitrate formats, but to also create an adaptive delivery experience by allowing on-the-fly format conversion.  Your content can be streamed to Windows 8 applications, Windows Phone applications, Browsers (via Silverlight), iOS devices and android devices which covers a large majority of consumer need.

3. Development.  Generally, your streaming partner provides some flavor of SDK for interacting with their service as part of your application development and deployment.  One of the huge by-products by partnering with Azure for this type of application is that their services are native and integrated into the rest of your Azure platform. You can program Media Services using the OData-based REST APIs. You can build an application making REST API calls to Media Services from .NET languages or other programming languages. You can easily deliver your content to devices such as connected TVs, set-top boxes, Blu-Ray players, OTT TV boxes, and mobile devices that have a custom application development framework and a custom media pipeline.  Microsoft provides porting kits (for a fee) that allow you to code to the smooth streaming platform.

4. Ads.  Yes, you can integrate ads into your product using overlays.  This allows you to have both paid and free versions of your application if so desired.

At a glance, this seems pretty powerful.  I am going to dive in and investigate at a more detailed level to see what kind of possibilities this may offer moving forward.

Monday, February 4, 2013

Authorization Using WIF 4.5

I'd like to continue the topic of claims-based security using WIF 4.5, and talk about the authorization model and its options at a deeper level. First, just to ensure we are all using the same terminology when discussing items, I want to clarify "authorization" when I use it in this context. Authorization and authentication are still widely confused when discussing overall security methodology. They are both aspects of security, but they play completely different roles in the process.

Authorization vs. Authentication

Authentication is really just the process of having users log in so you can ensure they have the right to access the application. Authentication is the concept at work when you log in to any web application at all. By having an approved and active user account, and entering the proper credentials, the user is authenticated to use the application. In most cases, users are authenticated prior to authorization.

Authorization is the mechanism by which we evaluate whether an authenticated user has access to a specified modality (url, service, module or data element) within the application to which they are authenticated. For instance, an authenticated user may be an administrator which makes them authorized to change settings, post content, etc. While another authenticated user may be a guest, which makes them authorized to read public content. In its most simple form, authentication is who you are and authorization is what you are allowed to do.

Claims-based Authorization

As we discussed before, claims-based authorization is the approach where you write code to allow or disallow access based on logic that checks data called 'claims'. Remember that in the case of a role-based authorization, the only claim we actually used was the claim a user made about his or her roles. A role claim was used for us to decide if the current user 'is a' specific role. Let's walk through making access decisions using a claims-based authorization approach.
  1. A user arrives at your application and needs to be authenticated.
  2. WIF forwards the user to your identity provider.
  3. Once the user is authenticated, the original request is made again, but now there is a new security token attached to the request which contains data representing the user by using claims representing each granular piece of data. WIF attaches these new claims to the principal that represents the user so it can be referenced quickly and easily.
  4. Your application checks the claims via code to ensure the claims are met. These checks can be made via code, service calls, database, home-grown rules, or the native ClaimsAuthorizationManager.
  5. Your application decides whether or not to allow the request based on the claims:logic check.
  6. Your application grants the request if the outcome of your check is true and denies it if false.
The ClaimsAuthorizationManager is a new tool in WIF 4.5 that seems to be useful for black-boxing the logic for any claims-based authorization in your applications. It allows you to sniff incoming requests and wrap access with a check to custom logic which will then make authorization decisions based on the incoming claims. Much like any other good design principle, abstracting your authorization logic can only add to your applications ability to be dynamically responsive to changing authorization requirements. If you have to customize or change your authorization rules, using ClaimsAuthorizationManager will not affect the core application code base. Anytime you can separate logic into a stand-alone process and create a producer-consumer relationship, I think you are creating dynamism in the application. This is just another means for injecting flexibility to potentially deal with unforeseen changes without degrading the 'meat and potatoes' of your application. The ClaimsAuthorizationManager appears to be a great opportunity to allow authorization to be black-boxed inside a singularly purposed service entity, which can position your application to leverage centralized logic in this area.

Role-based Authorization

Role-based authorization is implemented by assigning users to user roles that have been defined for the application. This is the example that I used when talking about an administrator or a guest. Both of those are considered roles. When using this methodology, users are assigned 1:n roles within the system which can be checked at run time for derivation of access rights. You can check the roles of the user in a few different ways to ensure they are authorized for access. 
  • Checking IPrincipal.IsInRole(“RoleToCheck”). This is probably the most straight-forward and widely-used method. Since it returns a boolean indicating membership in the role, you can use it in your conditional statements at any place in your code as a security check.
  • Using PrincipalPermission.Demand(). When you make the Demand() call, the application will throw an exception if the demand is not met by the roles. This flows into standard try-catch-finally blocks and makes authorization just another exception in the block. Be warned that exceptions are much more expensive from a performance standpoint when compared to the IsInRole() method.
  • Using the <authorization> section in web.config. This really only works if you are blocking entire URLs against roles. This is the most strict, blanket level authentication so far. The upside is that it requires no code changes for implementation since it is part of the configuration file.
  • Using [PrincipalPermission(SecurityAction.Demand, Role = “RoleToCheck”)] attributes. The declarative method cannot be used in code blocks or within the service/method implementations as it is an actual attribute of the method itself. The method will throw an exception if the authenticated user doesn't belong to the role being demanded.
As mentioned above, when you call the IsInRole() method, the system checks behind the scenes to see if the current user has that role. In claims-aware applications, the role is expressed by a role claim type that should be available in the token. When a user is authenticated, the role claim can be issued by the identity provider STS or by a federation provider such as the Windows Azure Access Control Service (ACS). You can also turn arbitrary claims into role-type claims using the ClaimsAuthenticationManager component of WIF. This allows requests to be intercepted when an application launches, allowing you to inspect the tokens and even transform them by adding, changing or removing claims.

Monday, January 28, 2013

Claims-Based Identity and Authorization

As a follow-up to the previous post about security, I am examining a claims-based security model within WCF using the Windows Identity Foundation (WIF). In a claims-based application, a user is represented by a set of claims. The basic idea is that an external service is configured to give you any relevant information about the user as part of each request. This also includes some assurance that the identity data you receive comes from a trusted source by using some flavor of cryptography. This really flows into a good SOA design because you are basically decoupling your application from the logic of authentication, the storage and protection of user names, passwords and emails, and forced integration with in-house identity systems. In a claims-based paradigm, your application is making decisions for access and security using information from the authenticating system.

Claims

Claims are really just pieces of data associated with the currently authenticated user. These 'claims' from the authenticating service can consist of items such as the user name, email, security group membership, etc. When your application receives these claims, it enables you to cater the availability of content to the authenticated user. A very important point on which to be clear is that the claims made from the issuing service are only as trustworthy as that service itself. For example, you trust a claim made by your company’s domain controller more than you trust a claim made by, for example, Facebook. In that regard, WIF represents claims with a Claim type, which has an Issuer property that allows you to find out who issued the claim.

Tokens

The user delivers a set of claims to your application along with a request. In a web service, these claims are carried in the security header of the SOAP envelope. In a browser-based web application, the claims arrive through the HTTP request from the browser. The claims, regardless of the arrival method, are serialized, which is where why we need security tokens. A security token is really just a serialized set of claims that is digitally signed by the issuing authority. The signature is needed because it guarantees the issuing authority has generated the attached claims, which validates their authenticity. In other scenarios where that kind of security isn’t needed, you can use unsigned tokens. One of the core features in WIF is the ability to create and read security tokens. WIF and the .NET Framework handle all of the cryptographic work, and present your application with a set of claims that you can read.

Relying Party

When you build an application that relies on claims, you are building a relying party (RP) application. Synonyms for an RP include “claims-aware application” and “claims-based application.” Both web applications and web services can be RPs. An RP is nothing more than a consumer of tokens issued by an STS who reads the claims from tokens for use in security or access as it relates to the identity of the user. WIF offers inherent functionality to help you build RP applications.

Issuing Authority

It seems there are endless types of issuing authorities, but we really want to focus on security tokens that contain claims. This issuing authority is another application or service that is tasked with the issuance security tokens. This logic is responsible for having the insight needed to be able to issue the proper claims given the specific application and the user making the request, and might ultimately just be a pass-through to other services to receive claims and authenticate users.

Security Token Service (STS)

A security token service (STS) is the service that creates, signs, and issues any security tokens based on the WS-Trust and WS-Federation protocols. These protocols are really difficult to implement on a stand-alone basis, but WIF seems to handle the vast majority of this work. It appears that it is much easier to get STS up and running by leveraging WIF. You can use a pre-built STS such as Active Directory® Federation Services (AD FS) 2.0, a cloud STS such as a Windows Azure Access Control Service (ACS), or, if you want to issue custom tokens or provide custom authentication or authorization, you can build your own custom STS using WIF. The following is an example from Microsoft of a claims-based system.

Relying Partner Authentication Flow
This diagram shows a Web site (the relying party application, RP) that has been configured to use WIF for authentication and a client, a web browser, that wants to use that site.
  1. When an unauthenticated user requests a page their browser is redirected to the identity provider (IP) pages.
  2. The IP requires the user to present their credentials, e.g. username/password.
  3. The IP issues a token back to that is returned to the browser.
  4. The browser is now redirected back to the originally requested page where WIF determines if the token satisfies the requirements to access the page. If so a cookie is issued to establish a session so the authentication only needs to occur once, and control is passed to the application.
It seems that leveraging WIF as an STS provider is an easily achievable way to use a secure and standardized methodology of application security.

Tuesday, January 22, 2013

SOA and Security

We have talked about WCF at great length, but have focused mainly on the scalability and dependability of the Service-Oriented Architecture (SOA) itself.  One of the topics we haven't gotten into at a sufficient depth is security and service access management as an integral part of the SOA design.  I'd like to explore some of the options available for securing your services while adhering to the good design principles of SOA.  But first, I would like to discuss what it means to have security built in to your SOA.  We know that a well-designed SOA should be an architecture of loosely coupled components that can be distributed across platform, technology, and physical environments. Service components can be abstracted, grouped and presented to provide a single process, or to provide more complex user stories for a consuming application. Services are the preferred communication technique across application boundaries, including platform, deployment, and trust boundaries.  The key attributes of SOA are:
  • Interoperable. Components can be interoperable across platform and technology boundaries.  In fact, a well designed service should be totally agnostic to the technologies interacting with it.
  • Autonomous. Services are exposed as autonomous components that can be versioned and managed independently.  As with all good platform design, think of each service as a black box.
  • Abstracted. Services should be abstracted at a granular enough level so they can be grouped by another service or application to perform more complex operations as a single method.  This is what I often call a user story service layer.  Business logic can be abstracted and presented as specific component-like stories for targeted consumption.
  • Interface based. Interfaces are defined by message contracts and schemas. Operation calls and parameters are passed in XML message envelopes.  Stick to agreed upon standards here for maximum scalability and interoperability.
  • Location agnostic. Service components can be consumed from the same machine or distributed to remote machines. The service interface and logic is independent of the transport and protocol used to access the service.  This gives you many points to scale and inject redundancy for performance and dependability.
  • Discoverable. Services publish their interface in such a way that client applications can discover them and generate a proxy mechanism for consumption.

I try to adhere to the agreed upon four tenets of SOA from Microsoft architect Don Box:
  • Boundaries are explicit. Services are black-boxed and will never allow direct internal visibility.  All interaction comes from agreed upon messaging and interaction methods.
  • Services are autonomous. Each service is viewed autonomously with a complete disregard for any client activities or accompanying services.  While interaction is allowed and obviously required, see the first tenet.  These services should not be intimately aware of each other.
  • Services share schemas and contracts, not class. Services share contracts and schemas to communicate.  This is analogous to a menu in a restaurant.  All of the inner workings are abstracted to a set of choices and communicated with an agreed upon contract. 
  • Compatibility is based upon policy. Policy in this case means definition of transport, protocol, security, etc.  This is primarily where we are focusing today.
To focus in on the compatibility tenet, let's delve into security at a deeper level. Security is fundamentally about protecting assets. Assets may be physical items such as code sets, methods or a database, but also can be more nebulous, such as your brand.  It is important to recognize that security is a commitment, not a software feature, as it is a never-ending process. As you design services and applications, you need to identify potential threats and understand that each threat presents a degree of risk. Security is basically about mitigating those risks via restrictions and/or counter measures. When done effectively,  security is a combination of people, process, and technology.

Security is comprised primarily of the following ideals:
  • Authentication. Authentication is, at its base, the ability for a system to know who the user is.  It is the process of uniquely identifying the users of applications and services. Keep in mind that users of applications and services may be people, other services, processes, or computers. When reading security documentation or writing code, these 'users' are called Principles.
  • Authorization. Authorization is the equivalent of a key card.  Just as a key card gives its holder permission to enter certain rooms in a building, authorization manages the resources and operations that the authenticated client is permitted to access. These resources can include operations, physical storage (as granular as tables and rows), registry keys and other  configuration data. Operations are basically equivalent to the methods at any given layer of the SOA.
  • Auditing. Effective auditing and logging is the key to non-repudiation. Non-repudiation at its base is evidence.  If you have implementing effective auditing, a user or process will be unable to deny its activities. For example, in a medical system, auditing is required to make sure that a user cannot deny changing information in a specific patient chart.
  • Confidentiality. Confidentiality, or privacy, is the process of making sure that all data is private and confidential and cannot be viewed by unauthorized users who attempt to monitor the traffic across a network. Encryption is the most used method of confidentiality.  Primarily, you must ensure that the only users and processes who can view specific data, are the ones for whom it is intended.
  • Integrity. Integrity is the guarantee that data is protected from modification, be it accidental or malicious. Like privacy, integrity is a huge deal, particularly when there is sensitive data being passed across networks. Integrity for data in transit is typically provided by using hashing and message authentication codes.
  • Availability. From a security perspective, availability means that systems remain available for legitimate users.  There are some malicious individuals who will attempt to bring down your services and thus cause your real users to be unable to leverage the system.  The denial of service attack (DoS) is aimed at simply over-running your system and bringing it down. 
Some keys to building secure services include the following:
  • Identify the targets for security. You should think through all of the objectives you have for security. User stories are a good tool for gaining insight into the natural roles and levels of security that come from usage of your system.  Identify all assets that need security as well as the granularity to which security is applied.
  • Understand the possible threats. Try to identify the threats which are relevant for your scenarios and context. This is called 'Threat Modeling' and is a good practice which helps you identify the realistic  threats to your system. Your security targets will help you prioritize your threats and vulnerabilities. Using the threat model, architects and developers should address vulnerabilities, and QA should ensure that the developers have addressed the vulnerability.
  • Stay away from 'roll your own' security. Proven principles, patterns, and practices are the best place to start building a security model.  By using time-tested, proven principles, patterns, and practices, you can eliminate entire groups of security problems without needing to discover the specific vulnerability in your identification process. You should take advantage of the experience of others when it comes to security.  That being said, proven principles, patterns, and practices are a great starting point.  But like all other architectural paradigms, security is fact dependent and you should not just implement something off-the-shelf without going through the identification and threat processes.
  • Commit to security as an eternal process.  Security should be of paramount consideration at every stage of a service, application or software development life cycle. At every stage, targets should be defined, threats should be modeled and mitigating actions should be taken.  Security is not and will never be a 'set it and forget it' item.
I am going to dig deeper into some of the possible mechanisms for securing WCF services in a web environment in the near future.  As part of a current project, I am spending a lot of mental energy looking into the options.  I will post some of the opportunities and how to leverage them in the coming days and weeks.