How do you get a User Identity? - c#

Once a user is authenticated and authorized, the application can get information about the user by using the User object’s Identity property. The Identity property returns an object that includes the user name and role information.
Below is the code snippet which I have used to understand the concept:-
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = User.Identity.IsAuthenticated.ToString();
Label2.Text = User.Identity.Name;
Label3.Text = User.Identity.AuthenticationType;
}
Is there any other way to get the User Identity?

Please clarify if you are wanting something like the following below..
If you just want the users Identity.. from an ASP.NET WebPage when the Page_Load is called create a string[] and do something like the following
string strRawUser = Page.User.Identity.Name;
Then from there strRawUser will have something like "DomainName\UserName"
So you need to Split the string into an stringArray and get the string[1] value like this
string[] strRawUserSplitter = Page.User.Identity.Name.Split("\\");
Label2.Text = strRawUserSplitter[1]

You can also get the current user identity using Principal Object.

Related

Asp.net MVC Capture user name from authentication popup

I created Asp.Net Mvc web application w/c is using windows authentication.
My requirement is capture and log invalid login attempts but don't know how to do it. Tried to google but no luck.
List item
How to capture user name input from authentication popup?
List item
Is there setting to limit login pop up after consecutive login failed.
It works on Internet Explorer (IE),It display 401 unauthorized after 3 consecutive login attempts but Firefox and Mozilla do not have limits.
Here is what i tried so far.
Using below code,
List item
I'm trying to capture unauthorized error unfortunately event only fire when i click cancel for Firefox and Mozilla.
List item
It fires after 3 invalid attempts in IE but don't know how to get user name input.
Global.asax
protected void Application_EndRequest(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Response.Status.Substring(0, 3).Equals("401"))
{
//Capture user name for further processing
//
context.Response.ClearContent();
context.Response.Write("You are un authorized ");
}
}
Thanks in advance, hope someone can help.
Finally made it work, totally get rid of my first code using Application_EndRequest event.
Thanks to derloopkat.
Code on Global.asax Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
string currentUser = HttpContext.Current.User.Identity.Name;
Int32 expiryMin = Convert.ToInt32(ConfigurationManager.AppSettings["CacheExpirationInMinutes"]);
// call our procedure
auditLog(currentUser);
bool IsActive = accessMaintenance.IsActive(currentUser);
if (IsActive)
{
// handling if user is valid/not locked...
}
else
{
// Other handling if user is locked...
}
}
}
auditLog Procedure
private void auditLog(string user)
{
// Get logs from event viewer
string userName = ExtractUserAlias(user);
EventLog securityLog = new EventLog("Security");
var logOnAttempts = (
from log in securityLog.Entries.Cast<EventLogEntry>()
where log.EventID == 4625 || log.EventID== 4624 && log.ReplacementStrings[5] == userName
orderby log.TimeGenerated descending
select log
).Take(20).ToList();
//Store user logs to db if logs does not exists.
//Store in DB for reporting purposes
DataAccess db = new DataAccess();
foreach (var x in logOnAttempts)
{
string entryType = "";
switch (x.EntryType)
{
case EventLogEntryType.SuccessAudit:
entryType = "SuccessAudit";
break;
case EventLogEntryType.FailureAudit:
entryType = "FailureAudit";
break;
}
SqlCommand com = new SqlCommand();
com.CommandType = System.Data.CommandType.StoredProcedure;
com.CommandText = "Sp_LogUser";
com.Parameters.AddWithValue("#UserName", userName);
com.Parameters.AddWithValue("#EntryType", entryType);
com.Parameters.AddWithValue("#TimeGenerated", x.TimeGenerated);
com.Parameters.AddWithValue("#Details", x.Message);
db.ExecuteNonQuery(com);
}
// logic to to validate and lock user
SqlCommand com2 = new SqlCommand();
com2.CommandType = System.Data.CommandType.StoredProcedure;
com2.CommandText = "Sp_validateAndLockUser";
com2.Parameters.AddWithValue("#Username", #userName);
db.ExecuteNonQuery(com2);
}
Windows is already capturing and logging invalid logon attempts in Windows Event Log. This can be seen using the application Event Viewer under Windows Logs/Security. But we also can retrieve these logs using C#.
Open Visual Studio as administrator and add this code. Just for testing we're going to get last 10 records.
EventLog securityLog = new EventLog("Security");
var logOnAttempts = (from log in securityLog.Entries.Cast<EventLogEntry>()
where log.EntryType==EventLogEntryType.SuccessAudit
orderby log.TimeGenerated descending
select log
).Take(10).ToList();
Property Message of my last log says:
A logon was attempted using explicit credentials.
Subject:
Security ID: S-1-5-21-3657345512-3965846940-1053971979-1002
Account Name: Daniel_2
Account Domain: Acer
Logon ID: 0x29058
Account Whose Credentials Were Used:
Account Name: jjjjj
Account Domain:
Where "jjjjj" is the user name I typed when trying to log into the page, and Daniel_2 is my Windows account. This value can be easily extracted by means of property ReplacementStrings. In my case ReplacementStrings[5] gets me "jjjjj". I think the query for EventLog entries needs to be filtered by application and date time, so it only shows logons to your web application once it's deployed in IIS.

SetAttribute for value isnt working correctly

I've been trying to get SetAttribute with the webBrowser.Document for a while, and for some reason the webBrowser fields don't get filled in.
I'm certain that I have the ID's correct, but perhaps i'm just overlooking something. I am setting textfields for the netflix login website.
My code is as follows:
var emailField = webBrowser1.Document.GetElementById("email");
var passField = webBrowser1.Document.GetElementById("password");
emailField.SetAttribute("value", username);
passField.SetAttribute("value", password);
Thanks for any help, the username is a string which includes the email, and password contains the password, also in a string.
You should put your code in DocumentCompleted.
Example
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var emailField = webBrowser1.Document.GetElementById("email");
var passField = webBrowser1.Document.GetElementById("password");
emailField.SetAttribute("value", "123");
passField.SetAttribute("value", "456");
}
Try it again.

How to store login user id in asp.net?

i am new to asp.net. my question is that how one can save login userid in asp.net webform?
code i am writing in asp.net webform is:
foreach (var s in db.Users)
{
if (tbUserName.Text==s.user_name && tbPassword.Text == s.user_password)
{
if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
FormsAuthentication.SetAuthCookie(tbUserName.Text, false);
Response.Redirect("~/");
}
else
{
FormsAuthentication.RedirectFromLoginPage(tbUserName.Text, false);
}
flag = 1;
break;
}
else
flag=0;
}
if(flag==0)
{
tbUserName.ErrorText = "Invalid user";
tbUserName.IsValid = false;
}
}
As Tim said, you can get the authenticated user with
User.Identity.Name
You can also get the AuthenticationType and IsAuthenticated properties from the same object.
A suggestion would be to NOT query your DB for all of the users and then loop through them for the correct one. Based off of the user input, you should query the db for the one and only user which matches the form post.
Based off of what you wrote, it looks like the passwords are in clear text and not encrypted, which is a huge security issue. Being new to .Net, take a look at the .Net Membership Providers or SimpleMembership or a comparable pattern.
Good luck!
I would suggest you look at using the Session object to store the user ID. A Session will be available throughout that user's session on the site. Thus, you can call Session anywhere in your site's code to reference that user ID.
For example, to store the id, simply do this, pretend we're in Page_Load()
Session["UserId"] = userID // Or wherever you get the ID from.
then in your code behind, you can do this:
string userId = Session["UserId"]
If the user ID is a number, say an int, then you will need to cast the userID:
int userId = 0;
int.TryParse(Session["UserID"], out userID)
Quick dirty link to a Session example :
http://asp.net-tutorials.com/state/sessions/

Remember me in Login with Session

I tried remember me with session but I can not succeed. First of all is it possible?
in CheckedChanged method
if (CheckBox1.Checked)
{
Session["email"] = TextBox1.Text;
Session["pass"] = TextBox2.Text;
}
in pageload method
if (Session["email"].ToString() !=null && Session["pass"].ToString() !=null)
{
TextBox1.Text = Session["email"].ToString();
TextBox2.Text = Session["pass"].ToString();
}
but it doesnt work.
You can't use Session for this purpose. You should have to use Cookie to save the Remember Me status.
"Remember me" functionality is implemented by using persistent cookie.
You can't use Session object, because it will be automatically deleted after certain period of user inactivity.
Security note: Never store user password in plaintext format!
Btw: its better that you create a user class with two properties email and pass, and store that in one session element:
User myUser = new User();
myUser.Email = "test#test.com";
myUser.Pass = "123456";
session["user"] = myUser;
and you store the Remember me inside a cookie, with some credentials highly encrypted or salted hash, so when your user visits again you match the name and salted hash with the info you have in your database
change like this. as you are checking for the value. you cant access ToString() method , when null object is there .
if (!string.IsNullOrEmpty(Session["email"]) && string.IsNullOrEmpty(Session["pass"])) )
// then do with session objects.

Problems using captured access token to retrieve user's facebook information

I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

Categories