Wednesday 28 January 2015

Login with Active Directory User using ASP.NET / C# (LDAP Login)

Following is the steps to get Active Directory authentication using ASP.NET / C#

Step 1:
We have to create a <appSettings> in web.config file under <Configuration> tag of project.

eg.
<appSettings>
    <add key="DirectoryPath" value="LDAP://example.com"></add>
    <add key="DirectoryDomain" value="example"></add>
</appSettings>

//in above code example.com is the domain name 

Step 2:
We have to design a Login Page 

<table style="margin-top:5%">
<tr>
<td>
<h3 class="banner">Login</h3>
<h4>Domain : DOMAINNAME HERE</h4>
</td>
</tr> 
<tr>
<td>
<asp:TextBox CssClass="txt" placeholder="Username" ID="txtUserName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:TextBox CssClass="txt" placeholder="Password"  ID="txtPassword"  TextMode="Password" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button CssClass="btn" ID="btnLogin" runat="server" Text="Login
onclick="btnLogin_Click" />
</td>
</tr>
</table>

Step 3:

Code will in code behind of Login Page and Button Event we have to write following Code:

protected void btnLogin_Click(object sender, EventArgs e)
{
string dominName = string.Empty;
string adPath = string.Empty;
string userName = txtUserName.Text.Trim().ToUpper();
string strError = string.Empty;
try
{
foreach (string key in ConfigurationSettings.AppSettings.Keys)
{
dominName = key.Contains("DirectoryDomain") ? ConfigurationSettings.AppSetting[key]:dominName;
adPath = key.Contains("DirectoryPath") ? ConfigurationSettings.AppSettings[key] : adPath;
if (!String.IsNullOrEmpty(dominName) && !String.IsNullOrEmpty(adPath))
{
if (true == AuthenticateUser(dominName, userName, txtPassword.Text, adPath, out strError))
{
Response.Redirect("Welcome.aspx", false);
}
else 
{
Response.Write("Invalid Username and Password!");
}
dominName = string.Empty;
adPath = string.Empty;
if (String.IsNullOrEmpty(strError)) break;
}
}
}
catch
{}
}

if Authentication is success then it will redirect to the Welcome.aspx Page.
              

Tuesday 20 January 2015

Get Hostname / Windows Login Name IP Address in SQL Server

Following Code is given to get the name of windows login using IP Address:


declare @IP as varchar(15)
declare @command as varchar(1000) 

set @IP='192.168.1.0' 

SET @command = 'ping -a -n 1' + @IP 

Create Table #Output (Output varchar(150) default(''))

INSERT INTO #Output 
EXEC xp_cmdshell @command
Begin try 
Select top 1 Replace(LEFT([Output],CHARINDEX('[', [output])-2),'Pinging ','') as HostName from #Output where Output is not null 
End Try 
Begin catch 
Select 'Host name for:' + @IP +' could not be find'
End catch 

drop table #Output