I see many similar questions, but not a single good answer. I'm using Forms Authentication and I would like to find AD account (domain/username) of the user that is currently logged in. I'm complete beginner in this field, and I would apriciate an example of how to do it. Thanks in advance.
I Used this to get my User Name of the user
username = (Session["UserName"].ToString()).Split('\\');
pUsername.InnerText = username[1];
try getting it from the session the one that is used for validation u can get that there
or u can do one thing is that get it from the database through SP on LoginClick store it in session and get it back where u need it.
I got it like this.
LP.UserName = UserName;
DataSet dsUserName = LBLL.validate_user(LP);
if (dsUserName.Tables[0].Rows.Count > 0)
{
Session["UserName"] = dsUserName.Tables[0].Rows[0]["userName"].ToString();
Session["entityUID"] = dsUserName.Tables[0].Rows[0]["entityUID"].ToString();
Response.Redirect("~/index.aspx", false);
}
else
{
lblMsg.Text = "Invalid Credentials. Please contact administrator!";
}
using System.Web.Security; // this will give you access to membership.
Inside your event:
// 2 examples:
bool loggedIn = User.Identity.IsAuthenticated;
string un = User.Identity.Name;
Related
I have an Application where i need to find the current Log in Users Domain name in the server site, but my authentication mode is Form, kindly help me out.
Finally i thought a nice way of solving the problem, and got it done too.
By using JS we can get the current system details then store it into a hidden filed and we can access the current system domain name & user name in the server side.
function domain_Data() {
var comdetails = new ActiveXObject("wscript.shell");
var comusername = comdetails.ExpandEnvironmentStrings("%username%");
var comusername1 = comdetails.ExpandEnvironmentStrings("%UserDomain%");
var add = comusername1 + ":" + comusername;
alert(add);
document.getElementById("_hide").value = add;}
Please suggest or change some suitlable title for this question as i am not able to find one
I am using Facebook to allow the users to authenticate to my site.
I use Facebook Login Button and somehow i find out the user is authenticated or not.
I am developing my website in ASP.NET 4.0
I check whether the user is authenticate through Javascript.
The problem is how should i tell my server that this user is authenticated and assign some ASP.NET roles. I cannot use Ajax becuase of securoty reasons and might be a attack of Impersonation. This site may have transactions in the future so it need to be less security vunerable.
RIght now what i did is create a session using javascript and redirect to some other page and then assign roles but i am not statisfied with this method
Any help is appreciated.
The easiest way would be to use Page methods and Page methods call your service on server or authenticate directly.
http://www.geekzilla.co.uk/View7B75C93E-C8C9-4576-972B-2C3138DFC671.htm
To fix this, after facebook successfully authenticate the user i postback the website with the some arguments.
FB.api('/me', function (response) {
res_id = (response.id);
__doPostBack('SetSessionVariable', res_id + "$" + response.first_name + "$"+ response.last_name);
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
});
And in code i do :
string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];
string eventArgument = (this.Request["__EVENTARGUMENT"] == null) ? string.Empty : this.Request["__EVENTARGUMENT"];
if (eventTarget == "SetSessionVariable")
{
// Authenticate User
}
Using ASP.NET membership, if I want to get information for the current user, I can call MembershipUser.GetUser()
So, somehow the system must know the ID of the current user.
If this is correct, and all I want is the ID of the current user, is there a way to get it without returning all the user information from the database?
I know I can get the username of the current user using User.Identity.Name, but I need the ID.
The short answer is no you can't get only userID without retrieve whole user info when you use built-in membership provider, only by this
MembershipUser user = Membership.GetUser();
string UserID = user.ProviderUserKey.ToString();
But if you want to have method or property which retrieve only userID, you must re-implement your own membership provider or(it's simply) to implement IPrincipal interface
To return the UserId, use the command bellow in your controller:
User.Identity.GetUserId();
To return the UserName, use:
User.Identity.Name;
To return the user:
var user = db.Users.Find(User.Identity.GetUserId());
Please refer to the post: How to get current user, and how to use User class in MVC5?
As you've guessed, the Membership API doesn't support what you want out of the box. In the past, I've used a helper class instead of creating my own provider. In this case it's pretty simple, maybe something like this:
public static object GetUserId() {
return GetUserId(HttpContext.Current.User.Identity.Name, true);
}
public static object GetUserId(string userName) {
return GetUserId(userName, true);
}
public static object GetUserId(string userName, bool UpdateLastActivity) {
using (SqlConnection c = new SqlConnection(CONNECTION_STRING)) {
string sql = #"
DECLARE #UserId uniqueidentifier
SELECT #UserId=u.UserId
FROM dbo.aspnet_Applications AS a
,dbo.aspnet_Users AS u
,dbo.aspnet_Membership AS m
WHERE
a.LoweredApplicationName=LOWER(#ApplicationName)
AND u.ApplicationId=a.ApplicationId
AND u.LoweredUserName=LOWER(#UserName)
AND u.UserId=m.UserId;
IF #UserId IS NOT NULL AND #UpdateLastActivity=1
UPDATE dbo.aspnet_Users
SET LastActivityDate=#CurrentTimeUtc
WHERE UserId=#UserId;
SELECT #UserId
";
using (SqlCommand cmd = new SqlCommand(sql, c)) {
cmd.Parameters.AddWithValue("#ApplicationName", Roles.ApplicationName);
cmd.Parameters.AddWithValue("#UserName", userName);
cmd.Parameters.AddWithValue("#UpdateLastActivity", UpdateLastActivity);
cmd.Parameters.AddWithValue("#CurrentTimeUtc", DateTime.UtcNow);
object id = null;
c.Open();
id = cmd.ExecuteScalar();
return id != DBNull.Value ? id : null;
}
}
}
Above is pretty similar to what's done in the Membership API when calling GetUser()
You can use MembershipUser.UserName to get the user id or try calling Membership.GetUser(User.Identity.Name) and see if that works for you.
After looking into this further, it seems that the ASP.NET Membership API does not track the user ID after all. It must track just the user name (User.Identity.Name). The ID is not required because Membership.GetUser() can find a user from an ID or user name.
In fact, Membership.GetUser() must simply translate to Membership.GetUser(User.Identity.Name). Since it can obtain the current user from the user name, there is no longer any reason to assume that the current user ID is cached anywhere.
So it appears the ID is not loaded into memory, and the only way to obtain the ID is to load the data from the database (which means loading the entire user record when using the ASP.NET Membership API).
Consider
int userId = WebSecurity.CurrentUserId;
Credit: https://stackoverflow.com/a/15382691/1268910
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;
}
i am building site where there are three types of user. Admin,Merchant and Assitant User.
Where to store information so that my application will know which user has logged on( whether it is admin or assitant user or merchant)
Thank you
You want to look at ASP.NET Membership and Roles.
string path = DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("Membership.GetUser().UserName);
w.Flush();
w.Close();
}