Active Directory (AD) & Lightweight Directory Access Protocol (LDAP)

Thursday, 17 May 2012 00:04 by Harpreet

Active Directory (AD)
Active Directory is a directory service created by Microsoft for Windows domain networks. It is included in most Windows Server operating systems. Server computers on which Active Directory is running are called domain controllers.  

Active Directory serves as a central location for network administration and security. It is a database that keeps track of all the user accounts and passwords in your organization. It is responsible for authenticating and authorizing all users and computers within a network of Windows domain type, assigning and enforcing security policies for all computers in a network and installing or updating software on network computers. For example, when a user logs into a computer that is part of a Windows domain, it is Active Directory that verifies his or her password and specifies whether he or she is a system administrator or normal user.

Active directories are used by computer admins when managing end user tasks. This includes the management of user accounts, files and other packages while operating on a large network that other people are on. Rather than having to physically tend to each and every computer to apply updates or transfer files, software-related tasks can easily be relegated to an active directory.

The active directory also gives administrators the ability to grant or deny access to certain users. Access can also be given to specific file or application sets within a network structure. The framework of an active directory can be divided physically and logically. 

Physical Structure

·         Sites: Sites in Active Directory represent the physical structure, or topology, of your network. It is a set of computers well-connected by a high-speed network, such as a local area network (LAN). All computers within the same site typically reside in the same building, or on the same campus network. A single site consists of one or more Internet Protocol (IP) subnets.

·         Domain controllers (DCs): Domain controller is a server on a Microsoft Windows or Windows NT network that is responsible for allowing host access to Windows domain resources. The domain controllers in your network are the centerpiece of your Active Directory.  It stores user account information, authenticates users and enforces security policy for a Windows domain.

·         Global Catalog (GC): The global catalog is a distributed data repository that contains a searchable, partial representation of every object in every domain in a multi-domain Active Directory Domain Services (AD DS) forest. The global catalog is stored on domain controllers that have been designated as global catalog servers and is distributed through multi-master replication. Searches that are directed to the global catalog are faster because they do not involve referrals to different domain controllers

Logical Structure:

·         Forest: A forest is a collection of trees within an active directory which share a common categorization. It is also a representation of a boundary that allows groups, computers and users to access information and other network objects on.

·         Tree: A tree comes next under the forest hierarchy, and represents one or more domains on an adjoining namespace. A set of domain trees are also linked within a trust hierarchy.

·         Domain: One or more domains may be stored under a tree. A domain is easily recognized by it’s DNS namespace. Within these domains are single databases which are capable of being replicated within an active directory.

·         Organizational Units: These can give the hierarchy to a given domain, whether it be in geographical terms, or in a managerial manner within an organization. 

LDAP(Lightweight Directory Access Protocol):
LDAP is a directory service protocol that runs on a layer above the TCP/IP stack. It provides a mechanism used to connect to, search, and modify Internet directories.

The LDAP directory service is based on a client-server model. The function of LDAP is to enable access to an existing directory. 

Installing Active Directory:
To work with active directory, first we need to install Remote Server Administrator Tools (Remote Server Administration Tools enables IT administrators to remotely manage roles and features in Windows Server).

After installing RSAT, open Control Panel, click Programs, and then click Turn Windows features on or off under Programs and Features. 

In the Windows Features dialog box, select the remote administration snap-ins and tools that you want to install, and then click OK.

Open Active Directory Users and Computers:

1.      Click Start, and then click Run.

2.      In the Open box, type dsa.msc, and then click OK or open Control Panel, click Administrative Tools and then click Active Directory Users and Computers. 

The following figure shows how Active Directory Users and Computers appear on the screen.

Managing Active Directory using C#:
First of all, you must ensure that you have appropriate level of permission to access and interact with the directory. To get started, add a reference in your project to System.DirectoryServices.   

Now we will learn how to view users, how to check existing users, how to add users, how to delete users, and how to reset password.

1.      Setting up the connection

The code to connect to Active Directory is very simple.  We start by creating a new instance of the DirectoryEntry class.  Think of the Active Directory domain as a tree, the DirectoryEntry class lets us point to a specific node in the tree.  Referring to the screen shots above (Active Directory Users and Computers), we want to point to the Users node which is in domain contoso.com.

DirectoryEntry entry = new DirectoryEntry(LDAP://OU=Usres,DC=contoso,DC=Com);

2.      Does a User Exist?

Before you update any user information it is probably a good idea to find out if they actually exist in the Active Directory.

Suppose we want to check that a user IWAM_contos exists in our active directory or not. 

//connecting to active directory node
DirectoryEntry de2 = new DirectoryEntry(LDAP://CN=IWAM_conto,OU=Users,DC=contoso,DC=com);

//searching for the user
DirectorySearcher deSearch = new DirectorySearcher(de2); 

//filtering results according to our requirements
deSearch.Filter = "(&(objectClass=user))";

//collecting the results
SearchResult reslt = deSearch.FindOne();
if (reslt != null)
{
Console.WriteLine("exists");
} 

3.      Viewing Users and their Information

Suppose we want to view user’s name and their email id in domain contoso.com. 

//connecting to active directory node
DirectoryEntry entry = new DirectoryEntry("LDAP://OU=Users,DC=contoso,DC=Com"); 

//searching for  users
DirectorySearcher ds = new DirectorySearcher(entry); 

//filtering the results
ds.Filter = "(&(objectClass=user))"; 

//telling the query engine that we want user’s name and their email id
ds.PropertiesToLoad.Add("name");
ds.PropertiesToLoad.Add("userPrincipalName");

//collecting all results
SearchResultCollection results = ds.FindAll();

foreach (SearchResult result in results)
{
Console.WriteLine("{0} - {1}",
result.Properties["name"][0].ToString(),
result.Properties["userPrincipalName"][0].ToString());
} 

In above code, name and userPrincipalName are LDAP Active Directory attributes which are used to manage users in active directory. These are not only two, there are many more like:

·        Common Name – Also known as CN. It may appear as CN=Mike Hunt or whatever the name given to the attribute is. This attribute is made up of the givenName attribute joined to SN, or the surname attribute.

·        displayName – Sometimes confused with the common name, this can be applied to users within an Active Directory.

·        givenName – This is the first name of a user.

·        SN – This is the surname of a user.

·        description – What you may see within Active Directory computers and users.

·        objectClass – Defines whether an object is a user, computer, or a container. Can be an important top-level container.

·        objectCategory – Defines the schema of an object within an Active Directory.

·        userAccountControl – This function allows or denies an account from entering a server. A value of 512 allows an account to access the server, while 514 denies access.

·        userPrincipalName – The values attached to this attribute often look like an e-mail address. It must be unique in order to log into a forest.

·        location – Refers to the location of a user or resource. Can be particularly useful for networked devices like printers and other computers within a network. Can also be written as “l” on some directories.

·        department – Refers to the department within a company or organization.

·        company – Refers to the name of the company or organization.

·        C – Refers to the country or region. 

4.      Adding Users
For adding users, you should have administrator level permissions. Now suppose we want to add a user ‘Craig_Miller’ in organizational unit ‘Users’ of domain ‘contoso.com’. 

DirectoryEntry dir = new DirectoryEntry(LDAP://OU=Users,DC=contoso,DC=Com);

//creating a child node under the node 'Users' and its type is user
DirectoryEntry adduser = dir.Children.Add("CN=Craig_Miller", "user");
using (adduser)
{
//providing values for different attributes of the new user
adduser.Properties["Name"].Value = " Craig_Miller ";
adduser.Properties["userPrincipalName"].Value = Craig_Miller@contoso.com;
adduser.CommitChanges();
}

5.      Deleting Users
Suppose we want delete user ‘abc_xyz’ in organizational unit ‘Users’ of domain ‘contoso.com’.

 

//we want to delete user 'abc_xyz".so we are connecting to this
DirectoryEntry deluser = new DirectoryEntry(LDAP://CN=abc_xyz,OU=Users,DC=contoso,DC=Com);
//all information related to user 'amit_jain4 is deleted'
deluser.DeleteTree();
deluser.Close(); 

6.      Setting Password

Here we want to set password for user abc_xyz.

//connecting to the user for which we want to set password
DirectoryEntry oDE = new
DirectoryEntry("LDAP:// CN=abc_xyz,OU=Users,DC=contoso,DC=Com");

//invoking the method for changing password and providing new password
oDE.Invoke("SetPassword", new Object[] { "abc123" });
oDE.CommitChanges();
oDE.Close();

Categories:   ASP.NET
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Request Detection from Mobile

Wednesday, 16 May 2012 01:19 by Harpreet

Mobile devices – smartphones, feature phones, and tablets – continue to grow in popularity as a means to access the Web. For many web developers and web-oriented businesses, this means it’s increasingly important to provide a great browsing experience for visitors using those devices. For this, we need to develop separate applications for mobiles and make them available whenever a request comes from a mobile. One approach for doing this is to detect the request and redirect it to the mobile site. This article explains the way to determine if an HTTP request is coming from a mobile phone or desktop (or laptop). If it is from a mobile device then it will be redirected to a mobile site. So we need to write a small piece of code in main webpage to detect whether the user is from mobile phone or system.

The ASP.Net C# function to detect whether the request is from mobile device:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions; 

public partial class _Default : System.Web.UI.Page
{
    public static Boolean isMobile()
    {
        HttpContext curcontext = HttpContext.Current; 

        string user_agent = curcontext.Request.ServerVariables["HTTP_USER_AGENT"];
        user_agent = user_agent.ToLower(); 

        // Checks the user-agent
        if (user_agent != null)
        {
            // Checks if its a Windows browser but not a Windows Mobile browser
            if (user_agent.Contains("windows") && !user_agent.Contains("windows ce"))
            {
                return false;                
            } 

            // Checks if it is a mobile browser
            string pattern = "up.browser|up.link|windows ce|iphone|iemobile|mini|mmp|symbian|midp|wap|phone|pocket|mobile|pda|psp";
            MatchCollection mc = Regex.Matches(user_agent, pattern, RegexOptions.IgnoreCase);
            if (mc.Count > 0)
                return true; 

            // Checks if the 4 first chars of the user-agent match any of the most popular user-agents
            string popUA = "|acs-|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv|palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3c |wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda-|";

            if (popUA.Contains("|" + user_agent.Substring(0, 4) + "|"))
                return true;
        } 

        // Checks the accept header for wap.wml or wap.xhtml support
        string accept = curcontext.Request.ServerVariables["HTTP_ACCEPT"];
        if (accept != null)
        {
            if (accept.Contains("text/vnd.wap.wml") || accept.Contains("application/vnd.wap.xhtml+xml"))
            {
                return true;
            }
        } 

        // Checks if it has any mobile HTTP headers

        string x_wap_profile = curcontext.Request.ServerVariables["HTTP_X_WAP_PROFILE"];
        string profile = curcontext.Request.ServerVariables["HTTP_PROFILE"];
        string opera = curcontext.Request.Headers["HTTP_X_OPERAMINI_PHONE_UA"]; 

        if (x_wap_profile != null || profile != null || opera != null)
        {
            return true;
        } 

        return false;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!isMobile())
        {
            Response.Redirect("login.aspx"); 
        }
        else 
        {
           //redirect to mobile site       
        }
    }
} 

Categories:   ASP.NET
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

ASP.NET 4.0 Web Development Features – Part 1 (Core Services)

Tuesday, 15 May 2012 19:06 by Harpreet

Web.config File Refactoring:
The Web.config file that contains the configuration for a Web application has grown considerably over the past few releases of the .NET Framework as new features have been added, such as Ajax, routing, and integration with IIS 7. This has made it harder to configure or start new Web applications without a tool like Visual Studio. In .the NET Framework 4, the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty or to contain just the following lines, which specify for Visual Studio what version of the framework the application is targeting:

<.?xml version="1.0"?.
  <.configuration.
   <.system.web.
    <.compilation targetFramework="4.0" /.>  
   <./system.web.
  <./configuration.> 

Extensible Output Caching:
Since the time that ASP.NET 1.0 was released, output caching has enabled developers to store the generated output of pages, controls, and HTTP responses in memory. On subsequent Web requests, ASP.NET can serve content more quickly by retrieving the generated output from memory instead of regenerating the output from scratch. However, this approach has a limitation — generated content always has to be stored in memory, and on servers that are experiencing heavy traffic, the memory consumed by output caching can compete with memory demands from other portions of a Web application.

 

ASP.NET 4 adds an extensibility point to output caching that enables you to configure one or more custom output-cache providers. Output-cache providers can use any storage mechanism to persist HTML content. This makes it possible to create custom output-cache providers for diverse persistence mechanisms, which can include local or remote disks, cloud storage, and distributed cache engines. 

You create a custom output-cache provider as a class that derives from the new System.Web.Caching.OutputCacheProvider type. You can then configure the provider in the Web.config file by using the new providers subsection of the outputCache element, as shown in the following example:

 

<.caching.
  <.outputCache defaultProvider="AspNetInternalProvider".
    <.providers.
      <.add name="DiskCache" type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/.
    <./providers.
  <./outputCache.>
<./caching.>

 

By default in ASP.NET 4, all HTTP responses, rendered pages, and controls use the in-memory output cache, as shown in the previous example, where the defaultProvider attribute is set to AspNetInternalProvider. You can change the default output-cache provider used for a Web application by specifying a different provider name for defaultProvider. 

In addition, you can select different output-cache providers per control and per request. The easiest way to choose a different output-cache provider for different Web user controls is to do so declaratively by using the new providerName attribute in a control directive, as shown in the following example:

 

<.%@ OutputCache Duration="60" VaryByParam="None" providerName="DiskCache" %.> 

Specifying a different output cache provider for an HTTP request requires a little more work. Instead of declaratively specifying the provider, you override the new GetOuputCacheProviderName method in the Global.asax file to programmatically specify which provider to use for a specific request. The following example shows how to do this.

 

public override string GetOutputCacheProviderName(HttpContext context)

    if (context.Request.Path.EndsWith("Advanced.aspx")) 
       return "DiskCache"; 
    else 
        return base.GetOutputCacheProviderName(context);
} 

With the addition of output-cache provider extensibility to ASP.NET 4, you can now pursue more aggressive and more intelligent output-caching strategies for your Web sites. For example, it is now possible to cache the "Top 10" pages of a site in memory, while caching pages that get lower traffic on disk. Alternatively, you can cache every vary-by combination for a rendered page, but use a distributed cache so that the memory consumption is offloaded from front-end Web servers.

Auto-Start Web Applications:
Some Web applications need to load large amounts of data or perform expensive initialization processing before serving the first request. In earlier versions of ASP.NET, for these situations you had to devise custom approaches to "wake up" an ASP.NET application and then run initialization code during the Application_Load method in the Global.asax file.

 

A new scalability feature named auto-start that directly addresses this scenario is available when ASP.NET 4 runs on IIS 7.5 on Windows Server 2008 R2. The auto-start feature provides a controlled approach for starting up an application pool, initializing an ASP.NET application, and then accepting HTTP requests. 

IIS Application Warm-Up Module for IIS 7.5:
The IIS Application Warm-Up Module for IIS 7.5 makes warming up your applications even easier than previously described. Instead of writing custom code, you specify the URLs of resources to execute before the Web application accepts requests from the network. This warm-up occurs during startup of the IIS service (if you configured the IIS application pool as AlwaysRunning) and when an IIS worker process recycles. During recycle, the old IIS worker process continues to execute requests until the newly spawned worker process is fully warmed up, so that applications experience no interruptions or other issues due to unprimed caches. Note that this module works with any version of ASP.NET, starting with version 2.0.

 

To use the auto-start feature, an IIS administrator sets an application pool in IIS 7.5 to be automatically started by using the following configuration in the applicationHost.config file:  

<.applicationpools.
  <.add name="MyApplicationPool" startMode="AlwaysRunning" /.>
<./applicationpools.>

 

Because a single application pool can contain multiple applications, you specify individual applications to be automatically started by using the following configuration in the applicationHost.config file:  

<.sites.
  <.site name="MySite" id="1".
    <.application path="/" serviceAutoStartEnabled="true" serviceAutoStartProvider="PrewarmMyCache" .
      <.!-- Additional content --.
    <./application.
  <./site.>
<./sites.>

<.!-- Additional content --. 
<.serviceautostartproviders.
  <.add name="PrewarmMyCache" type="MyNamespace.CustomInitialization, MyLibrary" /.>
<./serviceautostartproviders.>

 

When an IIS 7.5 server is cold-started or when an individual application pool is recycled, IIS 7.5 uses the information in the applicationHost.config file to determine which Web applications need to be automatically started. For each application that is marked for auto-start, IIS7.5 sends a request to ASP.NET 4 to start the application in a state during which the application temporarily does not accept HTTP requests. When it is in this state, ASP.NET instantiates the type defined by the serviceAutoStartProvider attribute (as shown in the previous example) and calls into its public entry point. 

You create a managed auto-start type with the necessary entry point by implementing the IProcessHostPreloadClient interface, as shown in the following example:

 

public class CustomInitialization : System.Web.Hosting.IProcessHostPreloadClient

  public void Preload(string[] parameters) 
 
    // Perform initialization.  
  }
} 

After your initialization code runs in the Preload method and the method returns, the ASP.NET application is ready to process requests.

 

With the addition of auto-start to IIS .5 and ASP.NET 4, you now have a well-defined approach for performing expensive application initialization prior to processing the first HTTP request. For example, you can use the new auto-start feature to initialize an application and then signal a load-balancer that the application was initialized and ready to accept HTTP traffic. 

Permanently Redirecting a Page:
It is common practice in Web applications to move pages and other content around over time, which can lead to an accumulation of stale links in search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

 

ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example: 

RedirectPermanent("/newpath/foroldcontent.aspx");            

 

Search engines and other user agents that recognize permanent redirects will store the new URL that is associated with the content, which eliminates the unnecessary round trip made by the browser for temporary redirects. 

Shrinking Session State:
ASP.NET provides two default options for storing session state across a Web farm: a session-state provider that invokes an out-of-process session-state server, and a session-state provider that stores data in a Microsoft SQL Server database. Because both options involve storing state information outside a Web application's worker process, session state has to be serialized before it is sent to remote storage. Depending on how much information a developer saves in session state, the size of the serialized data can grow quite large.

 

ASP.NET 4 introduces a new compression option for both kinds of out-of-process session-state providers. When the compressionEnabled configuration option shown in the following example is set to true, ASP.NET will compress (and decompress) serialized session state by using the .NET Framework System.IO.Compression.GZipStream class. 

<.sessionState mode="SqlServer" sqlConnectionString="data source=dbserver;Initial Catalog=aspnetstate" allowCustomSqlDatabase="true" compressionEnabled="true" /.>

 

With the simple addition of the new attribute to the Web.config file, applications with spare CPU cycles on Web servers can realize substantial reductions in the size of serialized session-state data. 

Expanding the Range of Allowable URLs:
ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

 

<.httpRuntime maxUrlLength="260" maxQueryStringLength="2048" /.> 

To allow longer or shorter paths (the portion of the URL that does not include protocol, server name, and query string), modify the maxUrlLength attribute. To allow longer or shorter query strings, modify the value of the maxQueryStringLength attribute.

 

ASP.NET 4 also enables you to configure the characters that are used by the URL character check. When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error. In previous versions of ASP.NET, the URL character checks were limited to a fixed set of characters. In ASP.NET 4, you can customize the set of valid characters using the new requestPathInvalidChars attribute of the httpRuntime configuration element, as shown in the following example: 

<.httpRuntime requestPathInvalidChars="&lt;,&gt;,*,%,&amp;,:,\,?"  /.>     

 

By default, the requestPathInvalidChars attribute defines eight characters as invalid. (In the string that is assigned to requestPathInvalidChars by default, the less than (<), greater than (>), and ampersand (&) characters are encoded, because the Web.config file is an XML file.) You can customize the set of invalid characters as needed.  

Note ASP.NET 4 always rejects URL paths that contain characters in the ASCII range of 0x00 to 0x1F, because those are invalid URL characters as defined in RFC 2396 of the IETF (http://www.ietf.org/rfc/rfc2396.txt). On versions of Windows Server that run IIS 6 or higher, the http.sys protocol device driver automatically rejects URLs with these characters.

Extensible Request Validation:
ASP.NET request validation searches incoming HTTP request data for strings that are commonly used in cross-site scripting (XSS) attacks. If potential XSS strings are found, request validation flags the suspect string and returns an error. The built-in request validation returns an error only when it finds the most common strings used in XSS attacks. Previous attempts to make the XSS validation more aggressive resulted in too many false positives. However, customers might want request validation that is more aggressive, or conversely might want to intentionally relax XSS checks for specific pages or for specific types of requests.

 

In ASP.NET 4, the request validation feature has been made extensible so that you can use custom request-validation logic. To extend request validation, you create a class that derives from the new System.Web.Util.RequestValidator type, and you configure the application (in the httpRuntime section of the Web.config file) to use the custom type. The following example shows how to configure a custom request-validation class: 

<.httpRuntime requestValidationType="Samples.MyValidator, Samples" /.>

 

The new requestValidationType attribute requires a standard .NET Framework type identifier string that specifies the class that provides custom request validation. For each request, ASP.NET invokes the custom type to process each piece of incoming HTTP request data. The incoming URL, all the HTTP headers (both cookies and custom headers), and the entity bodies are all available for inspection by a custom request validation class like that shown in the following example: 

public class CustomRequestValidation : RequestValidator

  protected override bool IsValidRequestString(HttpContext context, string value,  
      RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)  
    {...} 
 }

For cases where you do not want to inspect a piece of incoming HTTP data, the request-validation class can fall back to let the ASP.NET default request validation run by simply calling base.IsValidRequestString. 

Object Caching and Object Caching Extensibility:
Since its first release, ASP.NET has included a powerful in-memory object cache (System.Web.Caching.Cache). The cache implementation has been so popular that it has been used in non-Web applications. However, it is awkward for a Windows Forms or WPF application to include a reference to System.Web.dll just to be able to use the ASP.NET object cache.

 

To make caching available for all applications, the .NET Framework 4 introduces a new assembly, a new namespace, some base types, and a concrete caching implementation. The new System.Runtime.Caching.dll assembly contains a new caching API in the System.Runtime.Caching namespace. The namespace contains two core sets of classes: 

·         Abstract types that provide the foundation for building any type of custom cache implementation.

·         A concrete in-memory object cache implementation (the System.Runtime.Caching.MemoryCache class).

 

The new MemoryCache class is modeled closely on the ASP.NET cache, and it shares much of the internal cache engine logic with ASP.NET. Although the public caching APIs in System.Runtime.Caching have been updated to support development of custom caches, if you have used the ASP.NET Cache object, you will find familiar concepts in the new APIs.  

An in-depth discussion of the new MemoryCache class and supporting base APIs would require an entire document. However, the following example gives you an idea of how the new cache API works. The example was written for a Windows Forms application, without any dependency on System.Web.dll.

 

private void btnGet_Click(object sender, EventArgs e) 
{  
  //Obtain a reference to the default MemoryCache instance. Note that you can create multiple MemoryCache(s) inside of a single application.  
  ObjectCache cache = MemoryCache.Default;     

  //In this example the cache is storing the contents of a file string  
  fileContents = cache["filecontents"] as string;

  //If the file contents are not currently in the cache, then the contents are read from disk and placed in the cache.  
  if (fileContents == null)  
 
    //A CacheItemPolicy object holds all the pieces of cache dependency and cache expiration metadata related to a single cache entry.  
    CacheItemPolicy policy = new CacheItemPolicy();       
    //Build up the information necessary to create a file dependency.  
    //In this case we just need the file path of the file on disk.  
    List filePaths = new List();  
    filePaths.Add("c:\\data.txt");       
    //In the new cache API, dependencies are called "change monitors". 

    //For this example we want the cache entry to be automatically expired if the contents on disk change.

    //A HostFileChangeMonitor provides this functionality.  
    policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));       

    //Fetch the file's contents  
    fileContents = File.ReadAllText("c:\\data.txt");       

    //And then store the file's contents in the cache  
    cache.Set("filecontents", fileContents, policy);       
  }  
  MessageBox.Show(fileContents); 
}   

Extensible HTML, URL, and HTTP Header Encoding:
In ASP.NET 4, you can create custom encoding routines for the following common text-encoding tasks:

 

·         HTML encoding.

·         URL encoding.

·         HTML attribute encoding.

·         Encoding outbound HTTP headers.

 

You can create a custom encoder by deriving from the new System.Web.Util.HttpEncoder type and then configuring ASP.NET to use the custom type in the httpRuntime section of the Web.config file, as shown in the following example: 

<.httpRuntime encoderType="Samples.MyCustomEncoder, Samples" /.> 

After a custom encoder has been configured, ASP.NET automatically calls the custom encoding implementation whenever public encoding methods of the System.Web.HttpUtility or System.Web.HttpServerUtility classes are called. This lets one part of a Web development team create a custom encoder that implements aggressive character encoding, while the rest of the Web development team continues to use the public ASP.NET encoding APIs. By centrally configuring a custom encoder in the httpRuntime element, you are guaranteed that all text-encoding calls from the public ASP.NET encoding APIs are routed through the custom encoder.

Performance Monitoring for Individual Applications in a Single Worker Process:
In order to increase the number of Web sites that can be hosted on a single server, many hosters run multiple ASP.NET applications in a single worker process. However, if multiple applications use a single shared worker process, it is difficult for server administrators to identify an individual application that is experiencing problems.

 

ASP.NET 4 leverages new resource-monitoring functionality introduced by the CLR. To enable this functionality, you can add the following XML configuration snippet to the aspnet.config configuration file. 

<.?xml version="1.0" encoding="UTF-8" ? .> 
<.configuration.>  
  <.runtime.>  
    <.appDomainResourceMonitoring enabled="true"/.>  
  <./runtime.>
<./configuration.>

Note: The aspnet.config file is in the directory where the .NET Framework is installed. It is not the Web.config file.

 

When the appDomainResourceMonitoring feature has been enabled, two new performance counters are available in the "ASP.NET Applications" performance category: % Managed Processor Time and Managed Memory Used. Both of these performance counters use the new CLR application-domain resource management feature to track estimated CPU time and managed memory utilization of individual ASP.NET applications. As a result, with ASP.NET 4, administrators now have a more granular view into the resource consumption of individual applications running in a single worker process. 

Multi-Targeting:
You can create an application that targets a specific version of the .NET Framework. In ASP.NET 4, a new attribute in the compilation element of the Web.config file lets you target the .NET Framework 4 and later. If you explicitly target the .NET Framework 4, and if you include optional elements in the Web.config file such as the entries for system.codedom, these elements must be correct for the .NET Framework 4. (If you do not explicitly target the .NET Framework 4, the target framework is inferred from the lack of an entry in the Web.config file.)

 

The following example shows the use of the targetFramework attribute in the compilation element of the Web.config file. 

<.compilation targetFramework="4.0"/.>

 

Note the following about targeting a specific version of the .NET Framework:

·         In a .NET Framework 4 application pool, the ASP.NET build system assumes the .NET Framework 4 as a target if the Web.config file does not include the targetFramework attribute or if the Web.config file is missing. (You might have to make coding changes to your application to make it run under the .NET Framework 4.)

·         If you do include the targetFramework attribute, and if the system.codeDom element is defined in the Web.config file, this file must contain the correct entries for the .NET Framework 4.

·         If you are using the aspnet_compiler command to precompile your application (such as in a build environment), you must use the correct version of the aspnet_compiler command for the target framework. Use the compiler that shipped with the .NET Framework 2.0 (%WINDIR%\Microsoft.NET\Framework\v2.0.50727) to compile for the .NET Framework 3.5 and earlier versions. Use the compiler that ships with the .NET Framework 4 to compile applications created using that framework or using later versions.

·         At run time, the compiler uses the latest framework assemblies that are installed on the computer (and therefore in the GAC). If an update is made later to the framework (for example, a hypothetical version 4.1 is installed), you will be able to use features in the newer version of the framework even though the targetFramework attribute targets a lower version (such as 4.0). (However, at design time in Visual Studio 2010 or when you use the aspnet_compiler command, using newer features of the framework will cause compiler errors).

Categories:   ASP.NET
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Authentication and Authorization - Part 2 (Windows authentication and IIS)

Monday, 14 May 2012 19:43 by Harpreet

Windows authentication and IIS:
For Intranet web applications, the most common authentication scenario is Windows Authentication. Windows Authentication avoids the need to create a login form within an application, and does not require end-users to manually enter their username/password credentials to login to the application.  Instead, ASP.NET and IIS can automatically retrieve and validate the Windows username of the end-user visiting the site in a secure way.  The benefit of this approach is that it improves the end-user customer experience since users don’t have to re-type their passwords, and/or maintain separate accounts.  It also allows companies to re-use a common security identity system across their entire corporate networks (Windows clients, servers, file-shares, printers, and web apps). 

If you select windows authentication for your ASP.NET application, you also have to configure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods:

Anonymous, Basic, Digest and Windows Integrated

1.      Anonymous Authentication

With Anonymous authentication, the server does not request the client to send user credentials. It is a good choice when your site or service is publicly available and you do not need to know the identity of the caller. Additionally, there are typically no browser restrictions which stem from incompatibilities with supported authentication mechanisms. When a site is configured for Anonymous authentication, all users are allowed access. It is important to note that although you may have IIS configured for Anonymous authentication, you may be authenticating at the ASP.NET layer, which is not true Anonymous authentication. This section assumes that both IIS and the application do not require a login. 

Typical usage scenarios
You should consider Anonymous authentication when:

·         You do not need to know the name and/or password of the caller for either login or business logic components.

·         The information you are protecting is considered "public." 

You should not consider Anonymous authentication when:

·         You are restricting your user base to require a login name and password.

Implementation
By default, IIS enables anonymous authentication and uses the IUSR_machinename user account with the password controlled by IIS.

Configure ASP.NET using the Web.config file to specify no authentication, or Windows authentication.

Performance

<.!-- Web.config file --.>

<.system.web.>

<.authentication mode="Windows" /.>

<./system.web.> 

Having an anonymous Web site and not using ASP.NET impersonation will give you the highest performing, but the least secure, application configuration.

2.      Basic
When IIS is configured for Basic authentication, it instructs the browser to send the user's credentials over HTTP. Passwords and user names are encoded using Base64 encoding. Although the password is encoded, it is considered insecure due its ability to be deciphered relatively easily. The browser prompts the user with a dialog box, and then reissues the original anonymous request with the supplied credentials, including the user name and password. A pop-up logon dialog box may or may not be appropriate, depending upon your user interface design requirements. Most Internet browsers support Basic authentication. 

Typical usage scenarios
You should consider Basic authentication when:

·         Your users have Windows NT Domain or Active Directory accounts.

·         You need to support multiple browser types, including Netscape Navigator and all versions of Internet Explorer (including the Pocket PC and Windows CE platforms).

·         You need to support authentication over the Internet.

·         You need to access the clear text password in your application code.

·         You need to support delegation. 

You should not consider Basic authentication when:

·         You require a secure login and are not using a secure channel, such as that provided by Secure Sockets Layer (SSL).

·         Your users are stored in a custom database, and do not have Windows accounts.

·         You require a customized form presented to the user as a login page.

Implementation
To implement Basic authentication, configure it within IIS and make sure that your users have "log on locally" permissions on the Web server. If you implement Basic authentication, you should also use SSL/TLS.

If your ASP.NET application needs to run as the user authenticated by Basic authentication, use the following Web.config file configuration.

<.!-- Web.config file --.>

<.system.web.>

<.authentication mode="Windows" /.>

<./system.web.>

3.      Digest
Digest authentication is new to Windows 2000 and IIS 5.0. This form of authentication encrypts the user's password information and provides a mechanism that helps prevent some common server attacks (such as a replay attack). Digest authentication does not send the credentials over the network using clear text as Basic authentication does. Instead, it uses a hashing mechanism called MD5 developed by RSA. Although it is a viable authentication option for Internet scenarios, the client and server requirements limit its widespread use. Unlike Basic authentication, and in a similar fashion to NTLM and Kerberos, IIS does not log on the user locally to the Web server so you cannot perform delegation. 

Typical usage scenarios
You should consider Digest authentication when:

·         Your Web server is running Windows 2000 and your users have Windows accounts stored in Active Directory.

·         All of your clients use either the .NET platform or Internet Explorer 5.x.

·         You need a stronger level of password encryption than that provided by Basic authentication.

·         You need to support authentication over the Internet. 

You should not consider Digest authentication when:

·         You have clients using platforms other than .NET or Internet Explorer 5.0 or later.

·         Your users do not have Windows accounts stored in Active Directory.

·         You require delegation.

Implementation
To use Digest authentication in Windows 2000, the server must have access to an Active Directory server that is set up for Digest authentication.  

Note: After configuring Active Directory to store passwords using reversible encryption, all users must change their passwords for Active Directory to store each password in this manner.

If you implement Digest authentication, you should also use SSL/TLS to defend against replay attacks.  

If your ASP.NET application needs to run as the user authenticated by IIS Digest authentication, use the following Web.config configuration.

<.!-- Web.config file --.>

<.system.web.>

<.authentication mode="Windows" /.>

<./system.web.>

4.      Integrated Windows Authentication
Integrated Windows authentication (using either NTLM challenge/response or Kerberos) involves authenticating a user with a Windows NT Domain or Active Directory account. Unlike Basic and Digest authentication, the encrypted password is not sent across the network, which makes this method very secure. If Active Directory Services is installed on the server and the browser is compatible with the Kerberos V5 authentication protocol, both the Kerberos V5 protocol and the challenge/response protocol are used; otherwise only the challenge/response protocol is used. It is best suited for an intranet environment, where both user and Web server computers are in the same domain and where administrators can ensure that every computer is running Microsoft Internet Explorer version 3.01 or later. 

Typical usage scenarios
You should consider Integrated Windows authentication when:

·         Your users have Windows NT Domain or Active Directory accounts.

·         Your application runs on an intranet (behind a firewall).

·         All of your clients are running Internet Explorer version 3.01 or later.

·         You need to perform delegation (this requires Kerberos).

·         You need a seamless logon procedure for domain users (for example, without pop-up logon dialog boxes). 

You should not consider Integrated Windows authentication when:

·         Your user accounts are stored in an external database rather than a Windows NT Domain database or Active Directory.

·         You need to support authentication over the Internet.

·         Your clients are using Netscape Navigator or other non-Microsoft browsers.

·         You need to obtain the client's clear text password

Implementation
To implement Kerberos or NTLM, configure IIS to use Integrated Windows authentication. If you need to support clients other than those running Internet Explorer, you may want to enable Basic authentication in conjunction with NTLM or Kerberos. To use Kerberos, you need to consider these specific details:

You must run the client and server computers on Windows 2000 or later, and they must be in a Windows 2000 or later domain.

·         You must enable the client's user account for delegation.

·         You must enable the service's account for delegation.

·         You must enable participating computers for delegation. 

If your ASP.NET application needs to run as the user authenticated by IIS using integrated Windows authentication, use the following Web.config configuration.

<.!-- Web.config file --.>

<.system.web.>

<.authentication mode="Windows" /.>

<./system.web.>

 

Implementing Windows Authentication

1.      For implementing windows authentication in IIS7, you need to check that windows authentication is installed or not. You can do this using

Programs and features ->Turn Windows features on or off and selecting the checkbox Windows Authentication from Security in IIS

It will look like the snapshot given below:

2.       After installing the Windows Authentication in your system, update your IIS in web application settings. Select Authentication and enable the Windows Authentication and any of the Basic, Integrated or Digest Authentication. And don’t forget to disable Anonymous Authentication, otherwise everyone will be able to login to your application. Here is the Snapshot:

 


3. After Authentication, you can specify the authorization rules as well. Select Authorization rules for the given application and allow or deny the users according to your requirements. If in the Allow rule you give access to All Users then everyone having valid username and password will be able to login to your application. And for validating users, it will look in the Active Directory of the server on which your application is running. The snapshots for this step are given below:

 

4.       Now in Web.config file, set the Authentication mode to Windows. Here is the code snippet:

You can also set the Allow and Deny rules in web.config as well. 

Now run the application, it will display the Windows Authentication dialog. If you cancel the login dialog it will display a Access Denied page. If you give the correct username and password, it will display your application page.

<.?xml version="1.0" encoding="UTF-8"?.>

<.configuration.>

<.system.web.>

       <.authentication mode="Windows".>

       <./authentication.>

      <.compilation debug="true" targetFramework="4.0" /.>

<./system.web.>

    <.system.webServer.>

        <.security.>

            <.authorization.>

                               <.add accessType="Allow" users="*" /.>

                <.add accessType="Deny" users="?" /.>

            <./authorization.>

        <./security.>

    <./system.webServer.>        

<./configuration.>

Categories:   ASP.NET
Actions:   E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

About me

Chat with Admin

Gmail: dotnetcracknews@gmail.com
Mobile: +91-9871115233

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar
Disclaimer

The articles documented here contain some material excerpted from net, I will try to make sure that I mention reference to those sites, but if I miss out on some areas it is not intentional.

© Copyright 2012