Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Best way to find the user roles

Posted on 2007-11-21
17
705 Views
Last Modified: 2013-12-16
Hi,
(ASP.NET, C#)
I have created login page with Active Directory. It is working good.

Now, once the user login, I would like to find out their userrole, for example, if the user is "Admin" or "User".

I would like to achieve this through active directory.. How do I acheive this... (if I can create a new group in the Active Directory??)
or can I create a table in my database and keep track of their userroles ...

Thanks..
0
Comment
Question by:neonlights
  • 8
  • 5
  • 4
17 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 250 total points
ID: 20328344
There is this:

User.IsInRole("Admin")

Bob
0
 
LVL 33

Expert Comment

by:raterus
ID: 20328613
Do what Bob says, however I would suggest you also include your domain.  I've ran into problems in the past when I didn't include this.

User.IsInRole("SOMEDOMAIN\Admin")
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20328642
Thank you, Michael.

It's a good thing that I have someone who is really to catch my oversights *WINK*.

Bob

0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 33

Expert Comment

by:raterus
ID: 20328721
A very rare event indeed, usually when I follow behind Bob I find out something I didn't ever know.
0
 

Author Comment

by:neonlights
ID: 20329940
Michael and Bob - Thanks...
I agree with Michael about Bob... "A very rare event indeed" ;-)

How do I know "Admin"?

Is this information coming from the Active Directory? I am new to Active Directory...
0
 

Author Comment

by:neonlights
ID: 20329951
since we have many groups.. do I have to create one more group...

and assign certain users to be "Admin" and Others to be "Users"?

Thanks again..
0
 
LVL 33

Expert Comment

by:raterus
ID: 20329960
"Admin" here would be the group name you've created in Active Directory.  You would need to know this before hand.

You, of course, can get a list of all groups the user is in, but this gets much trickier to code.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20329977
Here is some useful ActiveDirectory code:

using System.Collections.Generic;
using System.DirectoryServices;
using System.Collections;
 
public class ActiveDirectoryGroups
{
 
  public static List<string> GetUserRoles(string userContainerPath, string userName, string adminAccount, string adminPassword)
  {
    string userFilter = string.Format("(&(objectCategory=person)(sAMAccountName={0})", userName);
    List<string> roles = new List<string>();
 
    using (DirectoryEntry entry = new DirectoryEntry(userContainerPath, adminAccount, adminPassword, AuthenticationTypes.None))
    {
      using (DirectorySearcher searcher = new DirectorySearcher(entry, userFilter))
      {
        SearchResult result = searcher.FindOne();
        IEnumerable groups = (result.Properties["memberOf"]) as IEnumerable;
        if (groups != null)
          foreach (string dn in groups)
            roles.Add(dn);
      }
    }
 
    return roles;
 
  }
 
}

Open in new window

0
 

Author Comment

by:neonlights
ID: 20329980
I know how to find list of all groups:
I would like to assign one or two users to be "Admin" - they can change some data in the application..

I am kind of confused with "Admin"

        public String GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            userLoginName = _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
 
LVL 96

Expert Comment

by:Bob Learned
ID: 20330015
>>I am kind of confused with "Admin"
Wherein lies your confusion (I am confused)?

Bob
0
 
LVL 33

Expert Comment

by:raterus
ID: 20330026
It sounds like you just need to open up "Active Directory Users and Groups", find the group, and add some users to it.
0
 

Author Comment

by:neonlights
ID: 20330099
Thanks Bob for your code.

ok..

Let's say I create a new group called "MyApplicationX" and I will add 15 users to this group.

Then, in that group, I will give 2 users as Admin...

Then, from my login.aspx, I can get all the people belongs to "MyApplicationX" group and can check for User.IsInRole("SOMEDOMAIN\Admin")? right?

0
 
LVL 33

Assisted Solution

by:raterus
raterus earned 250 total points
ID: 20330147
You can't add an extra "Admin" option to users in a group, without hacking up your active directory schema (and you don't want to do that).

I would just create at most two groups here,

MyApplicationX
MyApplicationX_Admins

You can check the membership of these two groups to control access to your application.
0
 

Author Comment

by:neonlights
ID: 20330168
and one more question: Let's say I have created a table in my database, and I added all those 15 users in there.. and then, I  give them manually what kind of permission they have... Can I use it then? like this...

If get the value GetUserRoles, can I assign that to User.IsInRole("SOMEDOMAIN\" + GetUserRoles)?
I am new asp.net and c#.. please be patient.. if II make silly mistakes.
thanks again...

        public string GetUserRoles()
        {
            String SqlString;
            string connectionString;

           
            connectionString = ConfigurationManager.ConnectionStrings["AM"].ConnectionString.ToString();
            if ((connectionString == null))
            {
                throw new ProviderException("Connection string cannot be blank.");
            }

            SqlString = "Select [UserRole] From TblEmployee Where ";
            SqlString = SqlString + " (EmployeeName = @EmployeeName)";
            OleDbConnection oleDbConnection = new OleDbConnection(connectionString);
            OleDbCommand oleDbCommand = new OleDbCommand(SqlString, oleDbConnection);
            OleDbDataReader oleDbDataReader = null;

            oleDbCommand.Parameters.Add("@EmployeeName", OleDbType.VarChar, 255).Value = userEmployeeName;
            try
            {
                oleDbConnection.Open();
                oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.SingleRow & CommandBehavior.CloseConnection);

                if (oleDbDataReader.HasRows)
                {
                    oleDbDataReader.Read();
                    userRole= oleDbDataReader.GetString(0);
                }
                else
                {
                    userRole = "";
                    return userRole;
                }
            }
            catch (OleDbException e)
            {
                System.Diagnostics.Trace.WriteLine("[Fining User Role] Exception " + e.Message);
                userRole = "";
                return userRole;
            }
            finally
            {
                oleDbConnection.Close();
            }
            return userRole;
        }
0
 

Author Comment

by:neonlights
ID: 20330199
Racterus.... no, I do not want to hack.. loll
Now, I  understand.. I am very sorry - I was confused with "Admin" as a role.. "Admin" is a one of group name..

I will create

MyApplicationX
MyApplicationX_Admins

and use them... thanks again.
0
 

Author Comment

by:neonlights
ID: 20330392
Hi Bob,

Would you please let me know ... how do I call your code.. GetUserRoles..

Thanks
0
 

Author Comment

by:neonlights
ID: 20330410
never mind Bob.. I figured it out.. sorry for that.

Thanks again both.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

828 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