Saturday, 5 October 2013

Using Authorization Manager (AzMan) for Managing Roles and Permissions

AzMan is an Access Control framework which is used to define operations which can be grouped as task; these operations are the operations which are there in your application (Which can be performed by user). So with the help of AzMan one can manage roles by providing permissions on different roles for different operations. Users are assigned with the different roles and based on those roles permissions are granted to the user.

AzMan also provides you with the Management Console known as Microsoft Management Console (MMC) for managing operations, roles and permissions. One can configure the directly in Active Directory or in the form of XML.




As I mentioned it is a Role based Framework, so the cost and effort to use it for application security is very less and one of the interesting feature is that it can directly works with the Active Directory, where AD groups can directly be configured for the specified permissions.

AzMan is available from the time of ASP.NET, but it is still available in Windows 8 as well as Windows Server 2012. The Enterprise Library Security Application Block was built with AzMan wrapper, but the in the latest version of Enterprise Library does not have this, so one need to write down this wrapper by its own(Can Refer earlier version of Enterprise Library for the Code).

 How to use AzMan in ASP.Net Application

AzMan comes as a default installation in Windows 7 and Windows Server 2008 onwards. As I mentioned above AzMan policy store can be created in Active Directory or in XML.

AzMan Policy Store in XML


In Management console, click on “Actions” and select “Options”, here you have to make sure that you have selected “Developer Mode”; this is being done for creating a new policy, because New Policy can only be created in “Developer Mode”.


As soon as you will do that you will get an a new option under “Actions” Menu named “New Authorization Store”, open this Action and select “Authorization Store Type” as “XML” and provide the location of the XML File, where we will define the policies.


Now you will see the XML file you added under Authorization Manager on the left hand panel of the console, select your policy and right click and open “Properties”, We need to give administrator rights to the “Network Service” as ASP.NET application will use this account by default, if someone want to impersonate some other account, that can also be done.


Now we need to create a New Application (This is where we maintain the Groups, users, roles, permissions for a particular application. As we can apply a single policy to many applications, with each application having different mappings between Roles, users and permissions), in my case it is “SampleApplication”:


Now we will see how to create tasks and operations. For creating New Operations, Under the Policy select the application you want to create task for, in my case it is “SampleApplication”, under it, expand “Definitions” and select “Operation Definitions”, right click on it and select “New Operation Definition”.


I created three operations, “Edit”, “View”, and “Delete”.


Similarly for adding Tasks, Select “Task Definitions”, right click on it and “New Task Definitions”. Here we will create the new task and will map the operations with these tasks. Here I have created two new Tasks i.e. “Admin Tasks” and “Guest Task”.



Now we can create the Roles and associate them with the tasks and the Users. So we can give permission to a particular role on a task and then users can be assigned to a particular role so as providing the access to all the tasks mapped to that role.

Now for adding Roles, just Select “Role Definitions”, right click on it and “New Role Definitions”. Here we will create the new role and will map the tasks with these roles. Here I have created two new roles i.e. “Admin” and “Guest”. (One can also map the operations instead of mapping tasks).



Now for assigning users to the roles created above, select “Role Assignments” in the console tree, right click on it and select “New Role Assignment”, now select the role for which you want to map users.


Now you will see that the two new roles are added into the console tree under “Role Assignments”.


Now right click on each role and select the users from active directory so as to assign a role to the users.


Do it for both the roles, and with this you are done, now we can use the created policy i.e. “SamplePolicy” in your application. Before going into that for how to use it in application, first let’s have a look for how to use Active Directory with Policy Store directly.

Sample Policy:

<?xml version="1.0" encoding="utf-8"?>
<AzAdminManager MajorVersion="1" MinorVersion="0" Guid="2785f140-42e8-4dea-94a0-4fdb891b79a2">
  <AzApplication Guid="246370e3-4cc4-415a-8b65-1f59fb822dbc" Name="SampleApplication" Description="" ApplicationVersion="">
    <AzOperation Guid="fcfcdbe3-c009-43e0-bbcc-7eb79e588ed8" Name="Edit" Description="">
      <OperationID>1</OperationID>
    </AzOperation>
    <AzOperation Guid="9c61f00b-bbc6-46c9-9832-d244aee1b064" Name="View" Description="">
      <OperationID>2</OperationID>
    </AzOperation>
    <AzOperation Guid="48c35aaf-b922-491d-89cf-c6fd4040e7a6" Name="Delete" Description="">
      <OperationID>3</OperationID>
    </AzOperation>
    <AzTask Guid="7ee8ae15-6954-45bd-a29f-03907c46b3d8" Name="Admin Tasks" Description="" BizRuleImportedPath="">
      <OperationLink>48c35aaf-b922-491d-89cf-c6fd4040e7a6</OperationLink>
      <OperationLink>9c61f00b-bbc6-46c9-9832-d244aee1b064</OperationLink>
      <OperationLink>fcfcdbe3-c009-43e0-bbcc-7eb79e588ed8</OperationLink>
    </AzTask>
    <AzTask Guid="e0652d25-df48-4c90-baa2-3630da84ef71" Name="Guest Tasks" Description="" BizRuleImportedPath="">
      <OperationLink>9c61f00b-bbc6-46c9-9832-d244aee1b064</OperationLink>
    </AzTask>
    <AzTask Guid="4bce9fbd-9d3f-443c-b378-8d06c36046b1" Name="Admin" Description="" BizRuleImportedPath="" RoleDefinition="True">
      <TaskLink>7ee8ae15-6954-45bd-a29f-03907c46b3d8</TaskLink>
    </AzTask>
    <AzTask Guid="6596b838-8c78-47ab-b8c1-142ef68cd015" Name="Guest" Description="" BizRuleImportedPath="" RoleDefinition="True">
      <TaskLink>e0652d25-df48-4c90-baa2-3630da84ef71</TaskLink>
    </AzTask>
    <AzRole Guid="fe14f1c7-e7dd-47ed-8fe7-8524de4d263a" Name="Admin">
      <TaskLink>4bce9fbd-9d3f-443c-b378-8d06c36046b1</TaskLink>
    </AzRole>
    <AzRole Guid="79da2bfd-2072-4e26-815d-b0a9f7239d53" Name="Guest">
      <TaskLink>6596b838-8c78-47ab-b8c1-142ef68cd015</TaskLink>
    </AzRole>
  </AzApplication>
</AzAdminManager>


AzMan Policy Store in Active Directory

In Management console, click on “Actions” and select “Options”, here you have to make sure that you have selected “Developer Mode”; this is being done for creating a new policy, because New Policy can only be created in “Developer Mode”.


As soon as you will do that you will get an a new option under “Actions” Menu named “New Authorization Store”, open this Action and select “Authorization Store Type” as “Active Directory” and provide the Store location of the Active Directory, where we will define the policies.



The Store name is something like this:

msldap://servername:portnumber/CN=SampleApplicationStore, partition

Server name is name of the server, port number is the port on which Active Directory is setup, and Container Name (CN) can be anything of your choice. Partition name is the name of partition created while doing the setup of Active Directory.

Configure Application to use Policy Store

Now what I have done is, created a new application and in the “Web.Config” file added configuration for the Role Manager and provided the connection string in the application for connecting to AzMan policy store. The application name specified in the role manager is the same Application we created in the management console for the sample policy.


Now what I have done is that I will add three buttons on the Default page, we will now have a look how we can access the Policy store from the code and display the buttons for the user to which the role has been provided and hide for those who don’t have permissions.

Before starting we need add references for accessing AzMan store, Click on Add Reference for the Website or any other application you have created, select “COM” tab and add reference of “azroles 1.0 Type Libraries”


So now my Default.aspx looks like this:


And Default.aspx.cs is something like this(Please find inline comments in the code), Here we are first getting the logged in user and then I am trying to get the operations and then checking if the user have access on a particular operation or not.


If you are using windows authentication, user context can be created like this:

IAzClientContext userContext = azApp.InitializeClientContextFromName(name, domain, null);

One can use it as per the need, the logic can be separated out and can be written in better way depending upon the Application Architecture, this is only the sample code.

Hope it provides some help.

Wednesday, 25 September 2013

Metro Style Apps

Metro Style applications are the full screen applications designed to incorporate user needs, are platform independent, enable touch interaction(s) with the users, supports multi-tasking, support different languages and locales and can be uploaded to Windows Application store for downloads.

As suggested by Microsoft, a Metro app can be built in various languages like by using HTML, CSS and JavaScript, or by using XAML with C# (New Metro API(s) are provided by Microsoft). But these are just the languages in which one can create the Metro Apps, Metro actually is new API(s) provided by Microsoft which is the subset of the .Net Framework API(s) (Very much Similar to what Microsoft has done for Silverlight or Windows Phone) with User Interface designing.

Microsoft has put a lot of thought work for choosing the API(s) for Metro Style Apps, which also provides the ability to easily migrate an application into Metro Application.

Here is the example for how to create a Metro Style App using HTML + CSS + JavaScript as Language

Open Visual Studio 2012; create a new Project by selecting JavaScript as Application or Project template type. In this for a simple app I have selected Blank App as the template shown in the screenshot below, one can select in according to the requirement.



As soon as you are done with it, you will be asked for the Windows 8 Developer Licence if you don’t have it already, so go ahead and download it.

Now you will see with the blank template, it automatically created few folder and files:

  • A manifest file which will contain the information regarding your application like Application name, title and information about all the pages which exist in your application.
  • Some log images, one of which is “storelogo.png”, this image is the one which becomes the logo for your application on Windows Store.
  • Some CSS and JavaScript files along with a default.html page.


On launching the application the default page will get opened in the full screen mode. So now you are ready to make any changes on your page and include the new pages.

On opening the default.js file you will see some code already written into it, although it is self-explanatory, let’s see what it does:

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };

    app.start();
})();

All the code is written in anonymous function which will fire automatically on running the app; “strict” keyword is used here, so as to do the error checking into the code written.

Now there are two variables declared:

var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;

First one is “app” for storing the application i.e. Windows JS application object, next one is the “activation” which will contain the activation state of the application like if the application is a new launch or resumed from the state of suspension.

Next comes an event “onactivated”, this is the event which is fired every time on activation of the application whether it is launch or resume. And here you can see we can make check specific to the application state and do the coding as per the requirement.

Next is the “appcheckpoint”, which is fired whenever the application is going to be suspended, anything which is required to be done before suspension comes here.

Adding Simple Button and handle click event:

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>SampleApplication</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>

    <!-- SampleApplication references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <div>
        Hi Abhishek Jain
       <br />
        <input type="button" id="btnTestJavascriptEvent" value="Click Here to Test Javascript Event" />
        <br />
        Message from Javascript:
        <label id="lblMessage"></label>
    </div>
</body>
</html>

JavaScript:

app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }

        var testButton = document.getElementById('btnTestJavascriptEvent');
        testButton.addEventListener('click', TestButtonClick, false);
    };

    function TestButtonClick(e)
    {
        var messageLabel = document.getElementById('lblMessage');
        messageLabel.innerHTML = 'Message from Javascript Event...';
    }

Here I have created a method click handler for the button, and registered that handler to the button on application “onactivated” event. The “addEventListener” takes three arguments, first one is event type, second is the event handler and last is a Boolean value specifying if the event needs to be bubbled or not, “false” means allow event for bubbling.

Running App Screenshot:



May it provide a little help of how to create a simple HTML/JavaScript Metro App (For Downloading the Sample App, same I explained above, Refer: Sample Application); you can try much more at your end.