Solved

Limit Intranet Access by AD Group Membership

Posted on 2007-04-10
3
605 Views
Last Modified: 2008-02-01
I am working on a project at work that requires me to limit the access of an intranet page based upon the logged in user's membership in an Active Directory group. I have the following code that correctly authenticates to AD (written by a former employee), but I need to now get the list of the user's authorized groups and limit access based upon that. I've tried a few code snippets that I found online, but I haven't been able to get them to work. This will eventually be code we use Intranet-wide.

Example: userid=cromer is a member of group "ross" in AD
Generic loginform for intranet. User cromer tries to go to page ross.aspx and the login form comes up - if cromer is a member of group "ross" she gets in, otherwise she gets an error message that says she doesn't have permission to access that page.

Current AD User Authentication code on LoginForm.aspx.cs:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.DirectoryServices;

public partial class LoginForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.IsPostBack)
        {
            // Path to LDAP directory server.
            string adPath = "LDAP://sd_corp.local/DC=aert,DC=com";
            ActiveDirectoryLogin adAuth = new ActiveDirectoryLogin(adPath);

            try
            {
                if (true == adAuth.IsAuthenticated("sd_corp.local", Request.Form["UserName"], Request.Form["Password"]))
                {
                    // Create the authentication ticket
                    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(Request.Form["UserName"], true, 60);

                    // Now encrypt the ticket.
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                    // Create a cookie and add the encrypted ticket to the cookie as data.
                    HttpCookie adAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                    // Add the cookie to the outgoing cookies collection.
                    Response.Cookies.Add(adAuthCookie);

                    Session["displayName"] = adAuth.usrFullName;

                    FailureText.InnerHtml = "Successful login!";
                    FailureText.Style.Add("textJustify", "newspaper");
                    FailureText.Style.Add("margin", "5px");
                    FailureText.Style.Add("border", "3px coral solid");

                    // Redirect the user to the originally requested page
                    Response.Redirect(FormsAuthentication.GetRedirectUrl(Request.Form["UserName"], false));
                }
                else
                {
                    FailureText.InnerHtml = "Authentication failed, check username and password.";
                    FailureText.Style.Add("textJustify", "newspaper");
                    FailureText.Style.Add("margin", "5px");
                    FailureText.Style.Add("border", "3px coral solid");
                }
            }
            catch
            {
                FailureText.InnerHtml = "The system could not log you on. Make sure your User name is correct, then type your password again. Letters in passwords must be typed using the correct case."; // + ex.Message
                FailureText.Style.Add("textJustify", "newspaper");
                FailureText.Style.Add("margin", "5px");
                FailureText.Style.Add("border", "3px coral solid");

            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    }
 }
0
Comment
Question by:Hers2keep
3 Comments
 
LVL 12

Accepted Solution

by:
HugoHiasl earned 500 total points
ID: 18894841
If you set the Authentication of the site to not allow anonymous access, you can use the Roles.GetRolesForUser() Method.

Here's a tiny snippet from one of my projects:

HttpContext context = HttpContext.Current;

    if (context.User.Identity.IsAuthenticated) {
      returnValue = doLogin(userLogin);
      if (returnValue) {
        string[] userRoles = Roles.GetRolesForUser(((WindowsIdentity)context.User.Identity).Name);
        for (int i = 0; i < userRoles.Length; i++) {
          if (userRoles[i].Equals(ConfigurationManager.AppSettings["application.AdminADGroup"])) {
            // create second copy of userdata;
            context.Session["AdminUserData"] = context.Session["UserData"];
            context.Session["AdminRights"] = true;
          }
        }
      } else { ...



Make sure to add the following entries to your <system.web> section of your web.config:
      <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>
      <identity impersonate="true"/>

(restart iis after adding or stop the development webserver after adding.)

Best regards
Oliver
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now