Solved

Limit Intranet Access by AD Group Membership

Posted on 2007-04-10
3
606 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Edureka is one of the fastest growing and most effective online learning sites.  We are here to help you succeed.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

911 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

21 Experts available now in Live!

Get 1:1 Help Now