?
Solved

C# ASP.NET authentication and group listing vs AD successful but need a nudge in the right direction now pleae.

Posted on 2009-04-28
7
Medium Priority
?
416 Views
Last Modified: 2012-05-06
I have finished going through the msdn and ave successfully set up a login that checks active directory users and then lists the groups they are in via C#.  Now I would like to redirect the user to the appropriate page based on the group they are in.  I am not sure what resource to begin reading next to get this accomplished and was hoping someone might be able to send me in the right direction.
0
Comment
Question by:SystemApe
  • 5
  • 2
7 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 24258910
Are you using the ASP.Net Login control and Membership and Roles?
 
 
 If so, then you can register the "LoggedIn" event and run code something like this:

if Roles.IsUserInRole("Admin") 
  Redirect("AdminPage.aspx")
else if (Roles.IsUserInRole("PowerUser")
  Redirect("PowerUser.aspx")
else
  Redirect("NormalUser.aspx"

Open in new window

0
 

Author Comment

by:SystemApe
ID: 24260231
The Role Manager feature has not been enabled.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Configuration.Provider.ProviderException: The Role Manager feature has not been enabled.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace:


[ProviderException: The Role Manager feature has not been enabled.]
   System.Web.Security.Roles.EnsureEnabled() +1874402
   System.Web.Security.Roles.IsUserInRole(String username, String roleName) +105
   System.Web.Security.Roles.IsUserInRole(String roleName) +19
   FormsAuthAD.Next.Page_Load(Object sender, EventArgs e) in C:\Users\Enter\Documents\Visual Studio 2008\Projects\FormsAuthAD\FormsAuthAD\Next.aspx.cs:20
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +99
   System.Web.UI.Control.LoadRecursive() +50
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627

 
0
 

Author Comment

by:SystemApe
ID: 24260297
Here is the code inside my App Data  Directory
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:SystemApe
ID: 24260300
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.Collections;
using System.DirectoryServices;

namespace FormsAuthAD
{
    public class LdapAuthentication
    {
        private string _path;
        private string _filterAttribute;

        public LdapAuthentication(string path)
        {
            _path = path;
        }
        public bool IsAuthenticated(string domain, string username, string
  pwd)
        {
            string domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(_path,
                                                       domainAndUsername,
                                                         pwd);

            try
            {
                // Bind to the native AdsObject to force authentication.
                Object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                // Update the new path to the user in the directory
                _path = result.Path;
                _filterAttribute = (String)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                throw new Exception("Error authenticating user. " + ex.Message);
            }
            return true;
        }

        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();
            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                String dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount;
                     propertyCounter++)
                {
                    dn = (String)result.Properties["memberOf"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1),
                                      (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " +
                  ex.Message);
            }
            return groupNames.ToString();
        }


    }
}
0
 

Author Comment

by:SystemApe
ID: 24260530
I went in to my web.config and added <rolemanager enabled="true"> and now it only redirects to the NormalUser no matter what.  It doesn't recognize the groups only redirects to the else statement
0
 

Author Comment

by:SystemApe
ID: 24262229
working on setting up azman....had no idea it tied into our AD domain =)
0
 
LVL 21

Accepted Solution

by:
MogalManic earned 1500 total points
ID: 24269377
You can also use the results of your GetGroups() method to search to see if use has role

the UserHasRole method could be something like this:
    private Boolean UserHasRole(string roleName)
    {
        string[] Groups=GetGroups().Split(',');
        foreach(string group in Groups)
        {
            if (group.Equals(roleName, StringComparison.CurrentCultureIgnoreCase))
                return true;
        }
        return false;
    }

Open in new window

0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Question has a verified solution.

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

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Integration Management Part 2
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…

807 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