Share via


How to Create an Intranet Site Using ASP.NET MVC

This topic describes how to create an intranet application using ASP.NET MVC and how to secure it using Windows authentication and authorization.

Authentication is the process of identifying who users are when they visit a Web site. Authentication is typically used in combination with authorization. Authorization is the process of determining whether a user has permissions to access a particular resource or to perform some action. For example, when an end user accesses a URL using a browser, ASP.NET can authenticate the user and then examine the authorization rules for the requested resource to determine whether the user has permission to access it.

In intranet applications inside your corporate domain, you typically use Windows authentication. Windows authentication enables Web applications in a Windows domain to take advantage of the domain infrastructure for authenticating users. However, do not use Windows authentication if users who must be authenticated access your Web site from behind firewalls and proxy servers.

In this tutorial, you will implement authorization using explicit user authorization and using the built-in AspNetWindowsTokenRoleProvider class, which uses Windows groups as roles.

In order to complete this tutorial, you will need:

  • Microsoft Visual Web Developer 2010 or Microsoft Visual Studio 2010. To install Microsoft Visual Web Developer 2010 SP1, you can use the Web Platform Installer.

  • ASP.NET MVC 3 Tools Update. You can install this release from the following page: ASP.NET MVC 3 Tools Update

  • IIS 7 enabled on your computer, or IIS Express. For IIS 7, you must have the Windows Authentication feature installed. To install IIS and configure Windows authentication for IIS 7, see IIS 7 with Windows Authentication. To install IIS Express, you can use the Web Platform Installer.

Creating an Intranet Application

Visual Studio includes a template that you can use to create an ASP.NET MVC intranet solution.

To create a new ASP.NET MVC 3 Intranet Application project

  1. Open Visual Studio or Visual Web Developer.

  2. In the File menu, click New Project.

    The New Project dialog box is displayed.

    MVC New Project

  3. Under Installed templates, expand either Visual Basic or Visual C#, and then click Web.

  4. Select ASP.NET MVC 3 Web Application.

  5. In the Name box, enter Mvc3Intranet.

  6. In the Location box, enter a name for the project folder.

    Note

    IIS cannot run an ASP.NET project that has been created in the default Visual Studio project folder (C:\users\<user>\Documents\Visual Studio 2010\Projects). Select a folder where IIS can access the files, such as C:\Webs.

  7. Click OK.

    The New ASP.NET MVC 3 Project dialog box is displayed.

  8. Select the Intranet Application template.

    New IntraNet Project

  9. Click OK.

    The new ASP.NET MVC project is generated.

  10. Run the application.

    In the upper-right corner of the browser, you see your domain or workgroup user name.

    Welcome

  11. Open the layout file (Views\Shared\_Layout.cshtml or Views\Shared\_Layout.vbhtml) and locate the following HTML:

    <div id="title">
         <h1>My MVC Application</h1>
     </div>
     <div id="logindisplay">
         Welcome <strong>@Context.User.Identity.Name</strong>!
     </div>
    

    Replace it with the following markup:

    <div id="title">
        <h4> Environment.UserName: @Environment.UserName  
        @DateTime.Now.Millisecond.ToString() </h4>
    </div>
    <div id="logindisplay">
        Context.User.Identity.Name <strong>@Context.User.Identity.Name</strong>!
    </div>
    

    The Context.User.Identity.Name property returns the authenticated user's identity. When the application runs in IIS 7, and impersonation is disabled, the Environment.UserName property returns the identity of the application pool that the Web application is running in. For example, if the Web site is running in the default application pool, the name DefaultAppPool is displayed. If the ASP.NET v4.0 application pool is used, ASP.NET v4.0 is displayed.

Configuring the Web Server for the Project

By default, Visual Studio runs your Web application project using the Visual Studio Development Server. However, the Visual Studio Development Server does not support authentication failures that cause the operating system to prompt the user for credentials, so it is recommended you test your project using IIS or IIS Express. This section describes how to configure the Web project to use IIS 7, the Visual Studio Development Server, and IIS Express. Choose the procedure for the server that you want to use.

Note

You do not have to use IIS 7 for development. However, it is strongly recommended that you regularly test your Web application on IIS 7 if you plan on deploying your project to an IIS 7 server.

To configure the Web project to use IIS Express

  1. In Solution Explorer, right-click the project name and select Use IIS Express.

    Use IIS Express

    A dialog box is displayed that asks Do you want to configure this Web project to use IIS Express as its web server? A new site will be created on the IIS Express server to host your project.

  2. Click Yes.

  3. In Solution Explorer, select the project name and then press Alt+Enter to display the Properties window.

  4. In the Properties window, set Anonymous Authentication to Disabled and set Windows Authentication to Enabled.

    MVC 3 IISX Properties Window

  5. Run the application.

    Like the Visual Studio Development Server (and unlike IIS), IIS Express runs under the identity of the logged-in user. The Environment.UserName property is displayed as the identity of the logged-in user, namely you.

To configure the Visual Studio Development Server for Windows Authentication

  1. In Solution Explorer, right-click the project name and select Properties.

  2. Select the Web tab and then select the NTLM Authentication check box.

    Cassini NTLM

To configure the Web project to use IIS

  1. Verify that ASP.NET with Windows Authentication is enabled on your computer. The following illustration shows the Windows Features dialog box with the options selected that are required for this tutorial.

    Enable IIS 7.5

  2. Open IIS Manager. (In Windows, enter "iis" in the Search Programs and Files box and then select Internet Information Services (IIS) Manager.)

  3. In the Connections pane, right-click Default Web Site, and then select Add Application.

    IIS Add Application

    The Add Application dialog box appears.

  4. Enter an alias for the application and the path to the ASP.NET MVC intranet application that you created earlier in this tutorial.

    Add App Dlg

    The application pool must be a .NET Framework 4 application pool. If the default application pool is not .NET Framework Version: v4.0, select the ASP.NET v4.0 application pool. If your computer does not have a version 4.0 application pool, use the ASP.NET IIS Registration tool (Aspnet_regiis.exe) to register the .NET Framework 4. For more information, see ASP.NET IIS Registration Tool (Aspnet_regiis.exe). In the following illustration, the default application pool is V2 and requires you to configure the Web application to use the ASP.NET v4.0 application pool.

    C V4 App Pool

  5. In IIS Manager, select the new application in the Connections pane, and then in the Actions pane, click the Browse *:80 link.

    IIS Manager Browse

    Alternately, in a browser window, enter the URL for the application, such as https://localhost/MvcWA. The Environment.UserName property displays the application pool (either DefaultAppPool or ASP.NET v4.0).

    Welcome DefAppPool Contoso Rick

  6. In the URL in the browser, replace localhost with the name of your computer in order to verify that you have the correct fully qualified URL. You will use this URL in the next step.

  7. Test the URL that contains the computer name on another computer in your domain or work group.

    If you cannot access the Web application from a remote computer, you might need to configure the firewall on the computer that is serving the Web pages.

To enable the Web server access through the Windows firewall

  1. In the Windows Search programs or files box, enter "firewall".

  2. Select Allow a program or feature through Windows Firewall.

    start firewall

  3. Click Change settings and scroll to the bottom.

    Allow WWW through firewall

  4. Select World Wide Web Services (HTTP).

  5. Click OK.

  6. Verify that the URL for your ASP.NET MVC 3 Intranet application now works from a remote computer.

In the following procedure, you will configure the ASP.NET MVC 3 Intranet application to use Windows authentication on IIS 7.

To configure Windows authentication in IIS 7 for a Web application

  1. In IIS Manager, select the MvcWA application.

    In Features View, double-click Authentication.

    IIS manger authentication

  2. Right-click Anonymous Authentication and then click Disable.

    IISmgr Disable Anon

  3. Right-click Windows Authentication and then click Enable.

    Note

    If Windows authentication is not displayed, you must install the Windows authentication role service. For more information, see Install Windows Authentication.

Adding User and Group Access to a Controller

In this section, you will add action methods to a controller and restrict the controller so that only specific users and groups can access it. You typically restrict access by using groups and not specific user accounts, because users often change more frequently than groups.

To add user accounts and groups

  1. Run the ASP.NET MVC application you created earlier in this tutorial.

    The browser displays your domain or workgroup name. In the following illustration, the user name is "CONTOSO\Rick". You will use your own user name to restrict access later in the tutorial.

    Welcome DefAppPool Contoso Rick

  2. Open a command window and enter the following command:

    cmd /k net user <user> /Domain

    For <user>, substitute your user name. The command will list the groups you belong to. Note a few of the group names for use later in the tutorial.

    The command gpresult /V will list all the groups in your domain or workgroup, not just the groups you belong to. You can run this command if you want to find groups that you do not belong to.

  3. Add two action methods to the home controller. For example, add an action method named VB_CS_Managers and one named VP.

  4. Apply the AuthorizeAttribute attribute to the action methods in the home controller, and specify a list (a comma-delimited list) of users and roles who can access the controller.

    The following example shows how to use the AuthorizeAttribute attribute to restrict access to the action methods by users and roles.

    using System.Web.Mvc;
    
    namespace Mvc3Intranet.Controllers {
        public class HomeController : Controller {
            public ActionResult Index() {
                ViewBag.Message = "Welcome to ASP.NET MVC!";
    
                return View();
            }
    
            [Authorize(Users = @"CONTOSO\Rick, CONTOSO\Keith, CONTOSO\Mike")]
            public ActionResult About()
            {
                return View();
            }
    
            [Authorize(Roles = @"CONTOSO\VBmanagers,CONTOSO\CSmanagers")]
            public ActionResult VB_CS_Managers()
            {
                return View();
            }
    
            [Authorize(Roles = @"VPs")]
            public ActionResult VP()
            {
                return View();
            }
    
        }
    }
    
    Public Class HomeController
        Inherits System.Web.Mvc.Controller
    
        Function Index() As ActionResult
            ViewData("Message") = "Welcome to ASP.NET MVC!"
    
            Return View()
        End Function
    
        <Authorize(Users:="CONTOSO\Rick, CONTOSO\Keith, CONTOSO\Mike")>
        Public Function About() As ActionResult
            Return View()
        End Function
    
        <Authorize(Roles:="CONTOSO\VBmanagers,CONTOSO\CSmanagers")>
        Public Function VB_CS_Managers() As ActionResult
            Return View()
        End Function
    
        <Authorize(Roles:="VPs")>
        Public Function VP() As ActionResult
            Return View()
        End Function
    
    End Class
    
  5. Create views for the action methods you added.

  6. Add two action links to the menu item in the layout file in order to make navigation simpler.

    The following example shows the completed markup.

    <div id="menucontainer">
        <ul id="menu">
            <li>@Html.ActionLink("Home", "Index", "Home")</li>
            <li>@Html.ActionLink("About", "About", "Home")</li>
            <li>@Html.ActionLink("VB & CS", "VB_CS_Managers", "Home")</li>
            <li>@Html.ActionLink("VP Only", "VP", "Home")</li>
        </ul>
    </div>
    
  7. In the browser, navigate to an action where you are authorized.

  8. In the browser, navigate to an action where you are not authorized.

    The following illustration shows the Windows Security dialog box that is displayed and that prompts for credentials for an account that is permitted to access the URL.

    Note

    If you are using the Visual Studio Development server, you are not prompted for credentials and you see only a blank page.

    Windows Security

Enabling Impersonation

An important security feature is the ability to control the identity under which the Web application code is executed. By default, ASP.NET executes all code using the application pool account. However, ASP.NET can use impersonation to run code in the context of an authenticated and authorized user.

When Windows authentication is enabled but impersonation is disabled, ASP.NET performs file access checks in the file authorization module using the credentials that are sent from the browser. Impersonation does not need to be enabled, because the FileAuthorizationModule module ensures that the requesting user is allowed read access or write access to the resource, depending on the request verb (for example, GET or POST) before executing the request. This behavior applies to any requests that enter managed code. In earlier versions of ASP.NET, accessing files based on URIs such as "Default.aspx" triggered the access check. In ASP.NET MVC applications, where access to resources is typically performed using extensionless URLs, this check typically does not apply, because there is not a physical file to check. In that case, the FileAuthorizationModule class falls back to checking access-control lists (ACLs) for the folder. However, checking the ACLs on a directory in an ASP.NET MVC application is typically not fine-grained enough, because a file-level check applies to all controllers and views in the folder. A better approach is to apply the AuthorizeAttribute attribute to the controllers or action methods that have to be secured.

The code that is illustrated in this tutorial does not require impersonation. You should enable impersonation only for the following reasons:

  • The application requires access to local resources through APIs like System.IO.File using the browser’s credentials.

  • The application implements advanced scenarios that involve remote resource access that relies on Active Directory and Kerberos.

You can use impersonation with Windows authentication in the following ways:

  • Windows authentication without impersonation. This is the default setting. ASP.NET performs operations and accesses resources by using your application's process identity, which by default is the application pool identity on Windows 7 and Windows 2008 R2. For more information, see Application Pool Identities.

  • Windows authentication with impersonation. With this approach, the Web application impersonates the authenticated user and uses that identity to perform operations and access local resources. When you configure your application for impersonation, an impersonation token for the authenticated user is attached to the Web request thread. As a result, all local resource access is performed using the caller's identity.

    Note

    Using Windows authentication with impersonation results in an impersonation token and an associated logon session that does not have network credentials. If you access this Web site from a browser while logged onto a different computer in the same domain and the Web site attempts to access network resources, you end up with a null session on the remote server and the resource access will fail. To access remote resources, you need delegation. For more information about how to use delegation, see How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0.

  • Windows authentication with fixed-identity impersonation. With this approach, you impersonate a specific Windows account to access resources using that identity. You should avoid this impersonation approach; instead, use a custom application pool with a custom service identity. For more information, see Application Pool Identities.

To configure impersonation

  1. In IIS Manager, select the MvcWA application.

  2. In Features View, double-click Authentication.

    IIS manger authentication

  3. Right-click ASP.NET Impersonation and select Enable.

    IISmgr enable impersonation

  4. Run the application.

    The Environment.UserName property displays the impersonated identity.

See Also

Other Resources

Application Pool Identities

IIS 7 Two-Level Authentication with Forms Authentication and Windows Authentication