KB/aspnet/active_directory_roles/ADRoleProvider.jpg' alt='Query Active Directory Using Asp' title='Query Active Directory Using Asp' />A look at the confidentiality bit and updated Dsacls utility round out this series on configuring your Active Directory permissions to hide confidential data.Images/image001.jpg' alt='Query Active Directory Using Asp' title='Query Active Directory Using Asp' />Introduction Here I will explain how to get userdetails from Active directory based on username using asp.Description One day I got requirement like to get user.Active Directory based on username using asp.ASP.NET,C. NET,VB.NET,JQuery,Java.Script,Gridview.Introduction Here I will explain how to get userdetails from Active directory based on username using asp.Description One day I got requirement like to get user details from Active directory based on username.For that first create one new website after that right click on website and select Add Reference option after that select System.Directory.Services from.NET tab and click ok now directory services reference has added to our application do you know why we have added this directory service to our application because by using this service we can get userdetails from Active directory.After that design your aspx page like this lt htmlxmlnshttp www.Head.Enter Username lt td lt td lt asp Text.Box.IDtxtusernamerunatserver lt asp Text.Box lt td lt tr lt tr lt td lt td lt td lt asp Button.IDbtn.SubmitrunatserverTextSubmitonclickbtn.SubmitClick lt td lt tr lt tr lt tdalignright First Name lt td lt td lt asp Label.IDlblfnamerunatserverFont Boldtrue lt asp Label lt td lt tr lt tr lt tdalignright Last Name lt td lt td lt asp Label.IDlbllnamerunatserverFont Boldtrue lt asp Label lt td lt tr lt tr lt tdalignright Email lt td lt td lt asp Label.IDlblemailrunatserverFont Boldtrue lt asp Label lt td lt tr lt table lt div lt form lt body lt html After that add these references in code behindusing System.Configuration using System.Directory.Services After completion of writing namespaces and write the following code in button click codebehind protectedvoid btn.SubmitClickobject sender, Event.Args estring connection Configuration.Manager.Connection.StringsADConnection.To.String Directory.Searcher dssearch new.Directory.Searcherconnection dssearch.Filter s.AMAccount.Name txtusername.Text Search.Result sresult dssearch.Find.One Directory.Entry dsresult sresult.Get.Directory. Entry lblfname.Text dsresult.Propertiesgiven.Name0.To. String lbllname.Text dsresult.Propertiessn0.To.String lblemail.Text dsresult.Propertiesmail0.To.String If you observe above code here I am getting active directory connection path from web.Strings lt addnameADConnectionconnection.StringLDAP ads.Strings Demo.If you observe above code to get firstname i used given.Name and for lastname I used sn these all are defined properties in active directory if we want to get the details address, work phone, home address etc each one having different LDAP property name check below table for LDAP property names in Active directory.Name.LDAP Provider Property Name.Syntax.First Namegiven.Name.String. Initialsinitials.String.Last namesn.String.Display namedisplay.Name.String. Descriptiondescription.String.Officephysical.Delivery.Office.Name. String.Telephone numbertelephone.Number.String. Other Telephone numbersother.Telephone.String.E mailmail.String.Web pagew.WWHome.Page. String.Other Web pagesurl.String.Streetstreet.Address.String. P.O. Boxpost.Office.Box. String.Cityl.String. Stateprovincest.String.ZipPostal Codepostal.Code.String. Countryregionc, co, country.Code.String. User logon nameuser.Principal.Name. Stringpre Windows 2.AMAccount.Name. String.Account disabled Account.Control.Boolean.User Profile pathprofile.Path.String. Logon scriptscript.Path.String. Home folder, local pathhome.Directory.String.Home folder, Connect, Drivehome.Drive.String. Home folder, Connect, To home.Directory.String.Titletitle.String. Online Convert Pdf To Word In Editable Formats on this page.Departmentdepartment.String.Companycompany.String.Managermanager.String.Mobilemobile.String.Faxfacsimile.Telephone.Number.String. Notesinfo.Using OWIN and Active Directory to authenticate users in ASP.Net MVC 5 application Trailmax Tech.UPD There is a part 2 of this blog post explaining how to do roles and fixing a minor issue with authentication.UPD If you are on Windows 1.System.IO. File.Not. Found.Exception The system cannot find the file specified, have a look on this page.Thanks to David Engel for this link.A while back I had to implement a login system that relied on in house Active Directory.I did spend some time on figuring out how to work this in the nicest possible ways.One of the approaches I used in the past is to slam Windows Authentication on top of the entire site and be done with it.But this is not very user friendly before showing anything, you are slammed with a nasty prompt for usernamepassword.And you need to remember to include your domain name in some cases.I totally did not want that on a new green field project.So here goes the instructions on how to do a nice authentication against your Windows Users or in house hosted Active Directory.For this project Ill use Visual Studio 2.But steps for VS2.Cant say anything nice about any earlier versions of Visual Studio I dont use them anymore.First create an MVC project and make sure you select No Authentication when you create the project Just after creation of a new project, I usually update all Nu.Get packages it is easier to update packages when project is empty, rather later down the line.You dont have to do this.Now install new Nu.Get packages.You will need the following and all their dependencies Microsoft.Owin.Security. Cookies.Microsoft.Owin. Host.System.Web. Now in your AppStart folder create Startup.Put this into that file using Microsoft.Owin.Owin.Startup. AttributetypeofMy.Project.Startup.My. Project.Startup.ConfigurationIApp.Builder app.Configure.Authapp.This will not compile because you dont have Configure.Auth method.Add another file in AppStart called Startup.Auth.System.Microsoft.Owin. using Microsoft.Owin.Security. Cookies.My.Project. public static class My.Authentication.String Application.Cookie My.Project.Authentication.Type.Startup. public void Configure.AuthIApp.Builder app.User.Manager into owin, because this is used in cookie invalidation.Use.Cookie. Authenticationnew Cookie.Authentication.Options.Authentication.Type My.Authentication.Application.Cookie.Login. Path new Path.StringLogin.Provider new Cookie.Authentication.Provider.Cookie. Name My.Cookie.Name. Cookie.Http.Only true. Expire.Time.Span Time. Span.From.Hours1. Lets see what weve done so far.Startup.Owin.Startup. Attribute attribute on top of the class this tells OWIN system what Configuration method required by OWIN is named My.Project.Startup.There are other ways of doing this.Second file Startup.Auth.OWIN configuration for authentication this is very similar to what youd see if you created a project with ASP.Net Identity authentication.Only Ive replaced the name of Authentication.Type with my own, stored in statically available constant well need this value elsewhere later.Also we are saying that OWIN should redirect unauthenticated requests to Login, but we dont have anything there at the moment.Lets create a controller for that.System.Component.Model. Data.Annotations.System.Web. Mvc.Active. Directory.Authentication.Controllers.Login.Controller Controller.Allow.Anonymous.Action.Result Index.View.Http. Post.Allow.Anonymous.Validate.Anti. Forgery.Token.Action.Result IndexLogin.View.Model model.TODO process login.Login.View. Model.Required, Allow.Html.Username get set.Required.Allow. Html.Data.TypeData. Type.Password.Password get set.And Index.Active.Directory.Authentication.Controllers.Login.View. Model.View.Bag. Title Login.Layout ViewsSharedLayout.Loginlt h.Form.Html. Begin.FormIndex, Login, Form.Method.Post, new class form horizontal, role form.Html.Anti. Forgery.Token.Html.Validation. Summarytrue, new class text danger.Html.Label. Form m.Username, new class col md 2 control label.Html.Text. Box. Form m.Username, new class form control.Html.Validation.Message.Form m. Username, new class text danger.Html.Label. Form m.Password, new class col md 2 control label.Html.Password. Form m.Password, new class form control.Html.Validation.Message.Form m. Password, new class text danger.Log in classbtn btn default.This will give us a nice login form To check if our authentication stuff works lets put Authorize attribute on one of the existing actions in Home.Controller Authorize.Action.Result About.View.Bag. Message Your application description page.View.Now if you navigate to HomeAbout you should be redirected to login page.It is important that this works.If you dont get login prompt, something is wrong and you need to go back re do missing steps.Two possible problems I can see here Login route does not point to Login.Controller or OWIN startup configuration is not called.All of above was easy now we need to come up with logic that actually does checking of username and password combination against AD.Before we start any further add System.Directory.Services.Account.Management as a Reference to your project.And now create this class using System.System.Directory.Services.Account.Management.System.Security. Claims.Microsoft.Owin. Security.My.Project. namespace Active.Directory. Cannot Connect As Sysdba Windows Xp . Authentication.Models.Ad.Authentication.Service.Authentication.Result.Authentication.Resultstring error.Message null.Error.Message error.Message.String Error.Message get private set.Boolean Is.Success String.Is.Null. Or. EmptyError.Message.IAuthentication.Manager authentication.Manager.Ad.Authentication.ServiceIAuthentication.Manager authentication.Manager.Manager authentication.Manager.Check if username and password matches existing account in AD.Authentication.Result Sign.InString username, String password.Context.Type authentication.Type Context.Type.Machine. authenticates against your Domain AD.Context.Type authentication.Type Context.Type.Domain. Principal.Context principal.Context new Principal.Contextauthentication.Type.Authenticated false.User.Principal user.Principal null.Authenticated principal.Context.Validate.Credentialsusername, password, Context.Options.Negotiate.Authenticated.Principal User.Principal.Find. By.Identityprincipal.Context, username.Exception.Authenticated false.Principal null.Authenticated user.Principal null.Authentication.ResultUsername or Password is not correct.Principal.Is. Account.Locked.Out. here can be a security related discussion weather it is worth.Authentication.ResultYour account is locked.Principal.Enabled.Has. Value user.Principal.Enabled.Value false.Authentication.ResultYour account is disabled.Create.Identityuser.Principal.Manager. Sign. OutMy.Authentication.Application.Cookie.Manager. Sign. Innew Authentication.Properties Is.Persistent false, identity.Authentication.Result.Claims. Identity Create.IdentityUser.Principal user.Principal.Claims.IdentityMy.Authentication.Application.Cookie, Claims.Identity.Default.Name. Claim.Type, Claims.Identity.Default.Role. Claim.Type.Add. Claimnew Claimhttp schemas.Active Directory.Add.Claimnew ClaimClaim.Types.Name, user.Principal.Sam. Account.Name.Add.Claimnew ClaimClaim.Types.Name. Identifier, user.Principal.Sam. Account.Name.String. Is.Null. Or.Emptyuser.Principal.Email.Address. identity.Add.Claimnew ClaimClaim.Types.Email, user.Principal.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |