Cannot acces users Active Directory password information on production server - asp.net

I'm developing an MVC application and I have a routine that gets the currently logged on users password info and it works fine on my PC but when I publish my application to a live server on the domain, I don't seem to be able to gain access to the AD information. I have used very similar code in a currently running asp.net web application and it works just fine. I compared security settings on both applications and they look identical. Here is the routine:
public int GetPasswordExpiration()
{
PrincipalContext domain = new PrincipalContext(ContextType.Domain);
string currUserName = WindowsIdentity.GetCurrent().Name;
UserPrincipal currLogin = UserPrincipal.FindByIdentity(domain, currUserName);
DateTime passwordLastSet = currLogin.LastPasswordSet.Value; //here is where it chokes***
int doyPasswordSet = passwordLastSet.DayOfYear;
int doy = DateTime.Today.DayOfYear;
int daysSinceLastset = (doy - doyPasswordSet);
int daysTilDue = (120 - daysSinceLastset);
return (daysTilDue);
}
I am an administrator on the domain so I think I have an application permissions issue, but since the failing application has the same permissions as the working application, I'm not sure where to look next. Any help is appreciated.

I'm answernig my own question because I want to post the code that works. Wiktor Zychla nailed it when asking if WindowsIdentity.GetCurrent().Name applied to the identity of the application pool rather than the logged in user. As a matter of fact it did, thanks Wiktor!
Here is the modified code that works. I did change the way I got the users identity (explained why below).
Controller Code:
using MyProject.Utilities; // Folder where I created the CommonFunctions.cs Class
var cf = new CommonFunctions();
string user = User.Identity.Name;
ViewBag.PasswordExpires = cf.GetPasswordExpiration(user);
Code in CommonFunctions
public int GetPasswordExpiration(string user)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal currLogin = UserPrincipal.FindByIdentity(ctx, user);
DateTime passwordLastSet = currLogin.LastPasswordSet.Value;
int doyPasswordSet = passwordLastSet.DayOfYear;
int doy = DateTime.Today.DayOfYear;
int daysSinceLastset = (doy - doyPasswordSet);
int daysTilDue = (120 - daysSinceLastset);
return (daysTilDue);
}
The one thing that clued me in was that I decided to just run all the code in my controller and when I did, I got a red squiggly saying "The name WindowsIdentity does not exist in this context":
string currUserName = WindowsIdentity.GetCurrent().Name;
Also, the reason I retrieved User.Identity.Name in the Controller and passed it to the function is because once I got things working and wanted to thin out my controller, I tried to get User.Identity.Name in the function but I got another red squiggly with the same message under User in this line:
string user = User.Identity.Name;
So I figure this is a .net thing and just went with getting the User.Identiy.Name in the controller, pass it to the function and all is well. This one really tested my patience and I hope this post can help someone else.

Related

Reading user's information in Active Directory from Dynamics AX using specific domain controller

We have a few domain controllers that can be used to read AD users information.
When domain name "mydomain.co.uk" is being used as AD domain, any of those few domain controllers are being picked to serve the purpose.
However, if changes in AD haven't been propagated across all domain controllers, no results are being returned.
To address the issue I've decided to always point to a specific domain controller, which is "dc1.mydomain.co.uk".
In C# that's easily done with something like this:
new PrincipalContext(ContextType.Domain,
"dc1.mydomain.co.uk:389",
"OU=Groups,DC=mydomain,DC=co,DC=uk",
domainUsername,
domainPassword)
However in X++ only "mydomain.co.uk" works:
static void validateDomain(Args _args)
{
xAxaptaUserManager Axmanage;
NetworkDomain networkDomain = "";
// Works
networkDomain = "mydomain.co.uk";
// Does not work
networkDomain = "dc1";
networkDomain = "dc1.mydomain.co.uk";
networkDomain = "dc1.mydomain.co.uk:389";
networkDomain = "LDAP://dc1.mydomain.co.uk:389/";
Axmanage = new xAxaptaUserManager();
info(strFmt("%1", Axmanage.validateDomain(networkDomain)));
}
How can I achieve same functionality with xAxaptaUserManager in MS Dynamics AX 2012 R3, if possible?
We're not on your network, so we can't really test everything, but if xAxaptaUserManager, which is a kernel class doesn't work, but you are able to do it in C#...just create an assembly "helper" that you call from AX.
See below links:
https://learn.microsoft.com/en-us/dynamicsax-2012/developer/how-to-add-a-reference-to-a-net-assembly
https://learn.microsoft.com/en-us/dynamicsax-2012/developer/net-interop-from-x
I should have said this before, and you may prefer this as a solution.
In AX, you can just call .NET code. I think you may have to put this in a server method in a class or table if it doesn't work right away.
System.DirectoryServices.AccountManagement.PrincipalContext principalContext =
new System.DirectoryServices.AccountManagement.PrincipalContext(System.DirectoryServices.AccountManagement.ContextType::Domain,
"dc1.mydomain.co.uk:389",
"OU=Groups,DC=mydomain,DC=co,DC=uk",
"username",
"password");

How to Get Current User Principal

I want to use Windows Authentication and get User info such as Givenname, Surname, etc.
I used UserPrincipal.Current in IIS and I got an exception, but IIS express looks fine.
I solved by using a Find Method:
var domain = new PrincipalContext(ContextType.Domain);
var currentUser = UserPrincipal.FindByIdentity(domain, User.Identity.Name);

Limitation on using PrincipalContext & DomainContext, to retrive Active directory users

I have added the following code inside my asp.net mvc web application model class, to retrive the current AD users:-
public List<DomainContext> GetADUsers(string term=null)
{
List<DomainContext> results = new List<DomainContext>();
string ADServerName = System.Web.Configuration.WebConfigurationManager.AppSettings["ADServerName"];
using (var context = new PrincipalContext(ContextType.Domain, ADServerName))
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
var searchResults = searcher.FindAll();
foreach (Principal p in searchResults)
{
if (term == null || p.SamAccountName.ToString().ToUpper().StartsWith(term.ToUpper()))
{
DomainContext dc = new DomainContext();
dc.DisplayName = p.DisplayName;
dc.UserPrincipalName = p.UserPrincipalName;
dc.Name = p.Name;
dc.SamAccountName = p.SamAccountName ;
dc.DistinguishedName = p.DistinguishedName;
results.Add(dc);
}
}
}
return results;
}
I am now on the development machine , where AD is on the same machine as the asp.net mvc web application runs. And there is no need to provide username or password to access the AD. But I have the following questions about using my above approach on production server :-
Will the same approach work well if the AD and the asp.net mvc (deployed on IIS ) are not on the same machine?
Will I be able to provide username and password to access the active directory?
What are the general requirements I should achieve to be able to allow the Domaincontext class to access AD on remote servers ?
Thanks I advance for any help.
Regards
I think you're asking if you're able to use the same code if the web server is not apart of the Active Directory domain. PrincipalContext does have an overload for username and password to allow for credentials to be used to connect, instead of relying on the machine having enough permissions to read from the directory.
As for permissions, grant as few as possible. I would get your system administrator involved to create a the account. You maybe able to use Service Accounts which were introduced in Windows Server 2008 to allow for the authentication to happen.

Active Directory Authentication

I am have made one web application in asp.net.In my project Authentication was done by matching the username and password in database.But now client ask me for the auto login in application with the help Of Active Directory authentication. Client ask suggest me to use the Email Id of user in AD for the authentication.
I tried to fetch the records in the AD, I could fetch the Fullname of user but I couldn't get the Email id,
I tried the code:
System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
string[] a = Context.User.Identity.Name.Split('\\');
System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
string Name = ADEntry.Properties["FullName"].Value.ToString();
Further more I Use DirectorySearcher but it genterates Error that Coulnot search the record in the client server..
I had the exact same situation while making a portal for a company.
If they dont want you to get into their AD then what you can do is to request for the NTLogins of the people who will be given access to the portal. make a simple table which have their NTLogin and simply authenticate using the system from which the portal is being accessed.
Check out the sample code i used.
// Checking if the user opening this page is listed in the allowed user list against their NT login.
String sUser = Request.ServerVariables["LOGON_USER"].ToLower();
sUser = sUser.Replace("wt\\", "");
//Authentication using a custom auth method.
DatabaseOperations authenticateUser = new DatabaseOperations();
if (!authenticateUser.authenticate(sUser))
{
//unauthorized users will be redirected to access denied page.
Server.Transfer("AccessDenied.aspx", true);
}
And making sure that you have authentication mode to windows in your web.config file
<authentication mode="Windows"></authentication>
Hope this helps.
For reading AD data, i use this class. It is setup for our AD, but basically you can just pass in all the "fields" you want to find, in the params.
But you need to know what field holds the email address. Sysinternals made a pretty good tool for browsing AD, to figure out what you are looking for, called ADExplorer.
But I don't understand why you need to look in the AD? Can you not assume that the user is already authenticated, if they are on the network, and then rely on the windows identity?
public static Hashtable GetAttributes(string initials, params string[] Attribute)
{
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://ADNAME");
DirectorySearcher ADSearcher = new DirectorySearcher(directoryEntry);
ADSearcher.Filter = "(sAMAccountName=" + initials + ")";
foreach (string para in Attribute)
{
ADSearcher.PropertiesToLoad.Add(para);
}
SearchResult adSearchResult = ADSearcher.FindOne();
Hashtable hshReturns = new Hashtable();
foreach (string para in Attribute)
{
string strReturn = "";
if (adSearchResult.Properties[para].Count == 0)
strReturn = "";
else
strReturn = ((ResultPropertyValueCollection)adSearchResult.Properties[para])[0].ToString();
hshReturns.Add(para, strReturn);
}
return hshReturns;
}

Facebook Connect and ASP.NET

I'm at step 8 of the authentication overview found here: http://wiki.developers.facebook.com/index.php/How_Connect_Authentication_Works
In particular, the user has logged into facebook via Facebook Connect and their web session has been created. How do I use the facebook developer toolkit v2.0 (from clarity) to retrieve information about the user. For example, I'd like to get the user's first name and last name.
Examples in the documentation are geared towards facebook applications, which this is not.
Update
Facebook recently released the Graph API. Unless you are maintaining an application that is using Facebook Connect, you should check out the latest API: http://developers.facebook.com/docs/
I had a lot of trouble figuring out how to make server side calls once a user logged in with Facebook Connect. The key is that the Facebook Connect javascript sets cookies on the client once there's a successful login. You use the values of these cookies to perform API calls on the server.
The confusing part was looking at the PHP sample they released. Their server side API automatically takes care of reading these cookie values and setting up an API object that's ready to make requests on behalf of the logged in user.
Here's an example using the Facebook Toolkit on the server after the user has logged in with Facebook Connect.
Server code:
API api = new API();
api.ApplicationKey = Utility.ApiKey();
api.SessionKey = Utility.SessionKey();
api.Secret = Utility.SecretKey();
api.uid = Utility.GetUserID();
facebook.Schema.user user = api.users.getInfo();
string fullName = user.first_name + " " + user.last_name;
foreach (facebook.Schema.user friend in api.friends.getUserObjects())
{
// do something with the friend
}
Utility.cs
public static class Utility
{
public static string ApiKey()
{
return ConfigurationManager.AppSettings["Facebook.API_Key"];
}
public static string SecretKey()
{
return ConfigurationManager.AppSettings["Facebook.Secret_Key"];
}
public static string SessionKey()
{
return GetFacebookCookie("session_key");
}
public static int GetUserID()
{
return int.Parse(GetFacebookCookie("user"));
}
private static string GetFacebookCookie(string name)
{
if (HttpContext.Current == null)
throw new ApplicationException("HttpContext cannot be null.");
string fullName = ApiKey() + "_" + name;
if (HttpContext.Current.Request.Cookies[fullName] == null)
throw new ApplicationException("Could not find facebook cookie named " + fullName);
return HttpContext.Current.Request.Cookies[fullName].Value;
}
}
I followed up on this concept and wrote a full fledged article that solves this problem in ASP.NET. Please see the following.
How to Retrieve User Data from Facebook Connect in ASP.NET - Devtacular
Thanks to Calebt for a good start on that helper class.
Enjoy.
Facebook Connect actually isn't too difficult, there's just a lack of documentation.
Put the necessary javascript from here: http://tinyurl.com/5527og
Validate the cookies match the signature provided by facebook to prevent hacking, see: http://tinyurl.com/57ry3s for an explanation on how to get started
Create an api object (Facebook.API.FacebookAPI)
On the api object, set the application key and secret Facebook provides you when you create your app.
Set api.SessionKey and api.UserId from the cookies created for you from facebook connect.
Once that is done, you can start making calls to facebook:
Facebook.Entity.User user = api.GetUserInfo(); //will get you started with the authenticated person
This is missing from the answers listed so far:
After login is successful, Facebook recommends that you validate the cookies are in fact legit and placed on the client machine by them.
Here is two methods that can be used together to solve this. You might want to add the IsValidFacebookSignature method to calebt's Utility class. Notice I have changed his GetFacebookCookie method slightly as well.
private bool IsValidFacebookSignature()
{
//keys must remain in alphabetical order
string[] keyArray = { "expires", "session_key", "ss", "user" };
string signature = "";
foreach (string key in keyArray)
signature += string.Format("{0}={1}", key, GetFacebookCookie(key));
signature += SecretKey; //your secret key issued by FB
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(signature.Trim()));
StringBuilder sb = new StringBuilder();
foreach (byte hashByte in hash)
sb.Append(hashByte.ToString("x2", CultureInfo.InvariantCulture));
return (GetFacebookCookie("") == sb.ToString());
}
private string GetFacebookCookie(string cookieName)
{
//APIKey issued by FB
string fullCookie = string.IsNullOrEmpty(cookieName) ? ApiKey : ApiKey + "_" + cookieName;
return Request.Cookies[fullCookie].Value;
}
The SecretKey and ApiKey are values provided to you by Facebook. In this case these values need to be set, preferably coming from the .config file.
I followed up from Bill's great article, and made this little component. It takes care of identifying and validating the user from the Facebook Connect cookies.
Facebook Connect Authentication for ASP.NET
I hope that helps somebody!
Cheers,
Adam
You may also use SocialAuth.NET
It provides authentication, profiles and contacts with facebook, google, MSN and Yahoo with little development effort.
My two cents: a very simple project utilizing the "login with Facebook" feature - facebooklogin.codeplex.com
Not a library, but shows how it all works.

Resources