Question

Active Directory Authentication

Asked by: asp_net2

Hello,

My Company uses Active Directory for all Authentication. I'm creating a very small application, but i need to authenicate users before they can proceed. How can i work with the Active Directory DB rather than using the Acitve Directory Provider that comes with ASP.NET. I would like to be able to create Groups in Active Directory and authenticate against Groups.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-04 at 08:31:15ID24871416
Topic

Programming for ASP.NET

Participating Experts
1
Points
500
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Authenication
    Is this possible with ASP? I'm new to ASP, but learning. I have read about using asp to not cache webpages, well my problem runs along those lines. I have anonymous authenication setup on my specific asp pages on my webserver (IIS) to control security, well you login in on...
  2. Trusted Authentication
    I need to understand Trusted Authentication. If a client says that they are going to use TA from their portals to access web/app/db servers for a web application, what does that mean? I need a thourough explanation not just links. Links are also welcome. I just read somethin...
  3. Windows Authentication asks to authenticate!
    I've been at this for a month now. ASP.Net 2.0, WAP model. IIS 6.0, Windows Server 2003. 1. My app has only 2 pages so far. Default.aspx calls Login.aspx. 2. I have windows authentication code in global.asax like this: Sub WindowsAuthentication_OnAuthenticate(ByVal Source ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: tgerbertPosted on 2009-11-04 at 08:45:42ID: 25741213

For example, if someone is a member of a group they may continue, otherwise not?

Add a reference to System.DirectoryServices, and refer to the System.DirectoryServices.ActiveDirectory namespace, in particular DirectorySearcher and DirectoryEntry.

You can get the users name with Request.LogonUserIdentity, then search for that username DirectorySearcher.

 

by: asp_net2Posted on 2009-11-04 at 08:52:41ID: 25741283

>> For example, if someone is a member of a group they may continue, otherwise not?
Correct!!

>> DirectorySearcher and DirectoryEntry
Can you possible show me a quick example? Or do you know of any online tutorials that show you how to handle what you are explaining?

Thanks in advance!

 

by: tgerbertPosted on 2009-11-04 at 09:00:18ID: 25741387

Actually, if you just want to determine group membership even easier:

using System;
using System.Security.Principal;
 
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(IsMemberOf("YOURDOMAIN\\Domain Admins"));
    }
 
    private bool IsMemberOf(string GroupName)
    {
        GroupName = GroupName.Trim().ToLower();
 
        foreach (IdentityReference group in Request.LogonUserIdentity.Groups)
        {
            if (group.Translate(typeof(NTAccount)).Value.ToLower() == GroupName)
                return true;
        }
 
        return false;
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: asp_net2Posted on 2009-11-04 at 09:05:06ID: 25741449

Well, I will plan on having them login to the application but I plan on adding certain users to certain groups. So I will have an OU in Active Directory called My Company and then a Group called Admins which i will then add certain users to the Admins Group. I then will have another Group called Users which i will once again add certain users to this group. If they are not part of Active Directory then they should see a Error message if they are a member and verified their credentials then they can proceed to the page they normal requested.

 

by: tgerbertPosted on 2009-11-04 at 09:09:19ID: 25741497

I wouldn't bother having them login.  Windows will handle that security when they press CTRL-ALT-DEL; disable Anonymous access on your website and enable Integrated Windows Authentication.

 

by: asp_net2Posted on 2009-11-04 at 09:14:10ID: 25741545

Ok, how would I code the two pages with different Groups to only restrict users based on the Groups?

 

by: tgerbertPosted on 2009-11-04 at 09:25:39ID: 25741669

As shown, with the IsMemberOf function (VB.Net version below).  In the Page_Load event check that they're a member of the required group, and if not redirect them to a nice-looking error page.

Imports System.Security.Principal
Partial Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsMemberOf("YOURDOMAIN\YourApp Admins") Then
            Response.Redirect("~/NotAuthorized.aspx")
        End If
    End Sub
 
    Private Function IsMemberOf(ByVal GroupName As String) As Boolean
        GroupName = GroupName.Trim().ToLower()
 
        For Each Group As IdentityReference In Request.LogonUserIdentity.Groups
            If Group.Translate(GetType(NTAccount)).Value.ToLower() = GroupName Then
                Return True
            End If
        Next
 
        Return False
    End Function
End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: asp_net2Posted on 2009-11-04 at 10:21:01ID: 25742186

ok, i'm going to create an OU and two Groups to test this out with. Do i need to make any changes to the web.config file?

Do i need to add the Page_Load code for each page that needs to authenticate against a group?

 

by: tgerbertPosted on 2009-11-04 at 11:06:30ID: 25742688

No, you shouldn't need to make any changes to web.config as I recall - use a simple test page to make suer that Request.LogonUserIdentity.Name gives you the correct username.

And yes, you'll need to check this in each applicable page's Page_Load.  In my web app I used a global.asax, and inside of the Session_Start event I check username and group memberships, then set a Session variable - that way in the subsequent pages' Page_Load I can just check if Session["IsUser"] or Session["IsAdmin"] etc is set.

 

by: asp_net2Posted on 2009-11-04 at 13:59:57ID: 25744448

Hi tgerbert,

Ok, i ran the following code above after creating my OU along with two groups and two users per group. When i run the i first go to my index.aspx on the root of the application. I have a link called users.asxp and admin.aspx. If i select either link i get the following error message below.


The trust relationship between this workstation and the primary domain failed.

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.SystemException: The trust relationship between this workstation and the primary domain failed.


Source Error:


Line 14:
Line 15:         For Each Group As IdentityReference In Request.LogonUserIdentity.Groups
Line 16:             If Group.Translate(GetType(NTAccount)).Value.ToLower() = GroupName Then
Line 17:                 Return True
Line 18:             End If
 

Source File: C:\inetpub\wwwroot\AD Authentication\admin\index.aspx.vb    Line: 16

Stack Trace:


[SystemException: The trust relationship between this workstation and the primary domain failed.
]
   System.Security.Principal.SecurityIdentifier.TranslateToNTAccounts(IdentityReferenceCollection sourceSids, Boolean& someFailed) +1243
   System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean& someFailed) +47
   System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess) +50
   System.Security.Principal.SecurityIdentifier.Translate(Type targetType) +129
   admin_index.IsMemberOf(String GroupName) in C:\inetpub\wwwroot\AD Authentication\admin\index.aspx.vb:16
   admin_index.Page_Load(Object sender, EventArgs e) in C:\inetpub\wwwroot\AD Authentication\admin\index.aspx.vb:7
   System.Web.UI.Control.OnLoad(EventArgs e) +115
   System.Web.UI.Control.LoadRecursive() +49
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

 

 

by: asp_net2Posted on 2009-11-04 at 16:21:30ID: 25745649

Hello,

I was able to get this code above to work, i replaced the response.redrect with a label control  saying "Access Denied".

How does the user enter there Username/Password. I don't see a box that pops up asking the user to enter there credentials, I have seen applications that use Integrated Authentication with a Widows Login box but this doesn't happen.

Also, I would like to COMPLETELY restrict access to the Admin/index.aspx and Users/index.aspx if a user is not part of the pages group in AD.

 

by: asp_net2Posted on 2009-11-05 at 06:02:51ID: 25749501

Hi tgerbert,

Are you still able to help me with this post?

 

by: tgerbertPosted on 2009-11-05 at 06:43:31ID: 25749907

Yup, just crawling outta bed. ;)

They enter their username/password when they press CTRL-ALT-DEL and log onto the computer; their Internet Explorer's are configured to automatically logon with their Windows username/password for web sites in the "Intranet Zone" (that behavior can be changed, on the client side, which is why you might see logon prompts for web sites using integrated Windows authentication).

You can use NTFS file permissions on the Admin/index.aspx and Users/index.aspx pages.

 

by: asp_net2Posted on 2009-11-05 at 06:57:07ID: 25750088

>> Yup, just crawling outta bed. ;)
Sorry :)

I'm going to send you a .txt file with the changes that i added to my web.config file along with the pages code and maybe you can take a look to see if i'm missing something.

Also, in IIS i enabled Windows Authentication and Anonymous Authentication and have all other authentications disabled. Is this okay or do i need to change something in IIS?

I also would like to ALWAYS prompt the user to enter there login credentials using the windows popup form when they try to access a restricted area.

Is there a way or place that i can also set a cookie for windows authentication?

 

by: tgerbertPosted on 2009-11-05 at 08:35:10ID: 25751190

>>  i enabled Windows Authentication and Anonymous Authentication and have all other authentications disabled. Is this okay or do i need to change something in IIS?

Make sure the pages you want to restrict access to have appropriate NTFS permissions set (i.e. the anonymous user can't read them). If you want to support browsers other than Internet Explorer I think you'll need to enable Basic authentication.



>> I also would like to ALWAYS prompt the user to enter there login credentials using the windows popup form when they try to access a restricted area.

Not gonna happen (not easily).  Even if you wrote your own authentication system using Web Forms, the clients' Internet Explorer will happily save the username/password, meaning a passer-by could still sit-down at an admins workstation and get access without knowing the password.  Although, if you want to pursue that route you can forcibly set some of the options in Internet Explorer to prevent automatic logon for sites in the Local Intranet or Trusted Zones (whichever the case may be).  Your other option would be to prompt for the users' current Windows password and then either using the LogonUser API function, or attempting to start a process (like notepad.exe) as that user with the supplied password.  Or, lastly, if you want to get away from using the Active Directory user database, create your own forms-based authentication system.



>> Is there a way or place that i can also set a cookie for windows authentication?

What do you mean by this?

 

by: asp_net2Posted on 2009-11-05 at 08:42:19ID: 25751280

ok, is there a way that i can display an error page if the user trys to access a restricted page but does not succeed?

For example, user visits index.aspx and clicks on the link labeled Admin which is located admin/index.aspx the windows logon box pops up and the user enters invalid credentials can i then send them to an error page stating that they supplied incorrect credentials or will the application just not allow them to access this page?

I'm use to useing SQL for authenication along with the SQL membership and Roles provider but my network admin wants me to use AD instead.

 

by: asp_net2Posted on 2009-11-06 at 05:50:17ID: 25759017

Hi tgerbert,

Well, i thought i had it working but i don't now :( I'm not even sure where to begin as for setting this up. Any help would be greatly appreciated.

 

by: asp_net2Posted on 2009-11-06 at 08:48:13ID: 25760751

are you able to help any further??

 

by: tgerbertPosted on 2009-11-06 at 09:35:22ID: 25761160

Yup, got my own stuff to take care of too. ;)

You can use ASP.Net's built-in Role Management system, I prefer not to as a matter of personal preference, but you may/may not find it easier to grant/deny access to pages; although doing so makes the pretty error page slightly more tricky, you can find more on that here: http://flimflan.com/blog/HttpModuleToAllowACustomErrorPageFor4012AccessDeniedInASPNET.aspx


In IIS you want Anonymous Access and Integrated Windows Authentication enabled.  Use NTFS file permissions to restrict pages that should be restricted.  This way anonymous users will still be able to get things like the "access denied" page.  Put a shared class in the App_Code folder, with a shared method: IsMemberOf.

 

by: asp_net2Posted on 2009-11-06 at 10:13:33ID: 25761500

Do i need the following information in my web.config ?

1.)  <authentication mode="Windows" />

2.) <location path="admin">
         <system.web>
             <authorization>
                 <allow roles="Leopards\Admins-Test"/>
             </authorization>
         </system.web>
      </location>

 

by: tgerbertPosted on 2009-11-06 at 11:42:47ID: 25762391

1.)  <authentication mode="Windows" />

Not sure if this matters if you're not using the ASP.Net Role Manager, it's in there by default and I've never had a need to change it.

2.)  <location path="admin">

Only if you want to use the built-in ASP.Net Role Manager, but then you'll have some work to do to enable a "pretty" access denied page (see link in my last post).  And it would look something more like the pieces below.


What I commonly do is to use a global.asax page, and handle the Session_Start event.  There I can check things like Active Directory and group membership, then set a session variable - then later I refer to that session variable to determine if access is allowed or not.

<authentication mode="Windows"/>
<roleManager defaultProvider="WindowsProvider" enabled="false" cacheRolesInCookie="false">
  <providers>
    <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider"/>
  </providers>
</roleManager>
 
<location path="Admin">
  <system.web>
    <authorization>
      <allow roles="YourDomain\TestAdmins"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>
 
<location path="Users">
  <system.web>
    <authorization>
      <allow roles="YourDomain\AppAdmins,YourDomain\AppUsers"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window

 

by: tgerbertPosted on 2009-11-06 at 11:43:45ID: 25762401

1.)  <authentication mode="Windows" />


If you do end up using the Role Manager then this is definitely necessary...

 

by: asp_net2Posted on 2009-11-06 at 12:08:24ID: 25762593

I don't know what the hell im doing wrong but i followed your examples and code perfectly and it still doesn't work.

 

by: asp_net2Posted on 2009-11-10 at 17:14:41ID: 31650054

tgerbert never got back to me.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...