I want to get the active directory login user in asp.net web forms.I used the below code snippet,but it won't work on either runtime or iis.
Request.ServerVariables["REMOTE_USER"].ToString();
Try using System.Web.HttpContext.Current.User.Identity; to get details of the authenticated user.
Use Directory Entry to get the user status.
string username = "";
string userpassword = "";
bool valid = false;
using (DirectoryEntry Direntry = new DirectoryEntry(path, username, userpassword))
{
using (DirectorySearcher Dsearch = new DirectorySearcher(Direntry))
{
Dsearch.Filter = "(cn=" + username + ")";
try
{
SearchResult adsSearchResult = Dsearch.FindOne();
if (adsSearchResult != null)
{
valid = true;
}
}
catch (Exception ex)
{
}
finally
{
Direntry.Close();
}
}
}
One additional change you may need to make is in the web.config file.
Change the authentication mode from Forms to Windows.
<authentication mode="Windows"/>
Documentation
Related
I have a .net core MVC controller that is downloading a file from a mapped drive on a server. It uses NetworkCredential to pass the username and password for the drive:
[HttpGet("[Action]")]
public IActionResult PdfContract(string fileName)
{
NetworkCredential theNetworkCredential = new NetworkCredential(_contractsUsername, _contractsPassword);
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(_contractsPath), "Basic", theNetworkCredential);
try
{
var path = _contractsPath + #"\" + fileName;
if (System.IO.File.Exists(path))
{
return new PhysicalFileResult(path, "application/pdf");
}
else
{
return NotFound(path);
}
}
catch (Exception exception)
{
return NotFound(exception.ToString());
}
}
this works fine when I run it locally in visual studio but when I put the code on the server it is trying to connect to the drive using the credentials of the box rather than those I am passing. Is there a way to force it to use the credentials?
After a lot of messing around I found a way to do this. If anyone else has this problem then this solution worked for me
https://www.c-sharpcorner.com/blogs/how-to-access-network-drive-using-c-sharp
I have made custom webapp using CMIS with which I am able to get the document from repository of alfresco and also able to upload document from my webapp into the repository of alfresco. But it is not checking for user authentication, if I try to login with random user who doesn't have access to the alfresco repository he/she is also able to login.
I am using below code:
public Session getSession() {
Properties prop = new Properties();
try {
prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
ALFRSCO_ATOMPUB_URL = "http://" + prop.getProperty("url") + ":"
+ prop.getProperty("port") + "/alfresco/service/cmis";
System.out.println(ALFRSCO_ATOMPUB_URL);
parameter.put(SessionParameter.USER, prop.getProperty("USER"));
parameter.put(SessionParameter.PASSWORD,
prop.getProperty("PASSWORD"));
// Specify the connection settings
parameter.put(SessionParameter.ATOMPUB_URL, ALFRSCO_ATOMPUB_URL);
parameter.put(SessionParameter.BINDING_TYPE,
BindingType.ATOMPUB.value());
parameter.put(SessionParameter.REPOSITORY_ID,
prop.getProperty("REPOSITORY_ID"));
SessionFactory factory = SessionFactoryImpl.newInstance();
session = factory.getRepositories(parameter).get(0).createSession();
return session;
} catch (CmisUnauthorizedException ex) {
System.out.println("you are unauthorized ");
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return session;
}
public boolean validateUser() {
Session session = getSession();
System.out.println("session " + session);
if (session != null) {
FolderBean.cmisSession = session;
return true;
}
return false;
}
Any advice would be appreciated!!!
You are reading username and password from config.properties file.You should change that with the username and password which are entered in your webapp.
Below line in your code reads property file.
prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
Below is reading username and password from property file.
parameter.put(SessionParameter.USER, prop.getProperty("USER"));
parameter.put(SessionParameter.PASSWORD,prop.getProperty("PASSWORD"));
Instead of that put here username and password of webapp which you are entering.
I'm trying to authenticate against AD using application mode (ADAM), but keep getting unknown username or bad password. If I test the login in LDP.exe it logs in no problem, on simple bind. I've trawled through all similar posts with the same issue, but have not resolved it, any suggestions what I should be checking for?
private bool ValidateActiveDirectoryLogin(string Username, string Password)
{
bool Success = false;
System.DirectoryServices.DirectoryEntry Entry = new System.DirectoryServices.DirectoryEntry("LDAP://localhost:389/OU=Users,O=TestDirectory", Username, Password);
System.DirectoryServices.DirectorySearcher Searcher = new System.DirectoryServices.DirectorySearcher(Entry);
Searcher.SearchScope = System.DirectoryServices.SearchScope.Subtree;
try
{
System.DirectoryServices.SearchResult Results = Searcher.FindOne();
Success = (Results != null);
}
catch (Exception ex)
{
Success = false;
throw;
}
return Success;
}
Determine what context your application is hitting AD with. If your ASP.NET application pool identity is one that is low privileged, it won't have enough permissions to query active directory. If you don't want to create a custom user to run the app pool as with appropriate permissions - you could use the LogonUser API to make your ValidateActiveDirectoryLogin call under the security context of that account.
Finally, you should consider using System.DirectoryServices.AccountManagement if you are using .NET 3.5 or above.
You can use code like
bool validCreds = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
validCreds = context.ValidateCredentials( username, password );
}
I have a code base web application that is connected to 2 databases. Depending on which login control a user uses to login, a different database is connected to the code. I am doing all of this by a cookie. This cookie is in a public class called AuthenticatedUser. The class looks like this:
public class AuthenticatedUser : System.Web.UI.Page
{
public static string ConnectionString
{
get
{
HttpCookie myCookie = HttpContext.Current.Request.Cookies["connectionString"];
return GetConnectionStringFromName(myCookie);
}
set
{
if (HttpContext.Current.Request.Cookies["connectionString"] != null)
{
ExpireCookies(HttpContext.Current);
}
var allCookies = HttpContext.Current.Request.Cookies.AllKeys;
HttpCookie cookie = new HttpCookie("connectionString");
cookie.Value = value;
cookie.Expires = DateTime.Now.AddYears(100);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
private static string GetConnectionStringFromName(HttpCookie myCookie)
{
try
{
string connectionStringName = myCookie.Value;
return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
catch
{
FormsAuthentication.SignOut();
}
finally
{
HttpContext.Current.Response.Redirect("/default.aspx");
}
return "";
} private static void ExpireCookies(HttpContext current)
{
var allCookies = current.Request.Cookies.AllKeys;
foreach (var cook in allCookies.Select(c => current.Response.Cookies[c]).Where(cook => cook != null))
{
cook.Value = "";
cook.Expires = DateTime.Now.AddDays(-1);
current.Request.Cookies.Remove(cook.Name);
cook.Name = "";
}
}
}
This seems to be working on my development machine, but when I tried to deploy it, any user that was using the "remember me" option on the site was getting a null reference error because they did not use the login control to obtain the cookie.
What is the best method to get around this? I was thinking if a user was logged in but the AuthenticatedUser class could not get a Connectionstring to log out the user to force them to use the login control again. What should I do?
Try use:
try
{
FormsAuthentication.SignOut();
}
finally
{
Response.Redirect("~/Home.aspx");
}
This way is preferable, for example if in some time you will decide not- cookie auth, but URL based - the FormsAuthentication will manage it gracefully.
I have a website which requires users to enter their corporate network username and password. It then looks for that account in Active Directory and gets a list of any email addresses associated with that account.
The problem I am having is that ONE incorrect password is locking out an account. Our domain policy is that an account will lock out after three incorrect entries, so I am assuming that I am doing something wrong in my code. I am not very knowledgeable about Active Directory or .NET DirectoryServices in general, which may be apparent from my code. Here it is:
public ArrayList AuthenticateActiveDirectory(string Domain, string UserName, string Password)
{
// An error occurs if the username/password combo does not exist.
// That is how we know it is not a valid entry.
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://" + Domain, UserName, Password);
object nativeObject = entry.NativeObject;
ArrayList emails = new ArrayList();
DirectorySearcher ds = new DirectorySearcher(entry);
ds.Filter = "samaccountname=" + UserName;
ds.PropertiesToLoad.Add("mail");
SearchResult sr = ds.FindOne();
if (sr.Properties["mail"] != null)
{
for (int email = 0; email < sr.Properties["mail"].Count; email++)
{
emails.Add(sr.Properties["mail"][email]);
}
}
return emails;
}
catch (DirectoryServicesCOMException) { throw; }
catch (Exception) { throw; }
}
I did some searching and found some code (thanks to Ayende Rahien for the solution) to use that just authenticates and doesn't search for emails or anything else. I am using this prior to the other function, and it seems to be working fine. I am guessing that my other code is hitting AD more than once - at least 3 times - which is resulting in the lockout. Here is the code I am using now to just authenticate:
private bool Authenticate(string domain, string user, string password)
{
try
{
using (DirectoryEntry de = new DirectoryEntry("LDAP://" + domain,
user, password))
{
return de.NativeObject != null;
}
}
catch
{
return false;
}
}