What is the best way to identify logged user? - c#

I was looking for the efficient way to track the logged users when using asp.net login control
if (!IsPostBack)
{
if (Membership.GetUser() != null)
{
var user = Membership.GetUser();
Session["user"] = user;
}
else
{
Session["user"] = "";
}
}
Any suggestions will be appreciated

why all this pain and why do you try to save it in the Session (which is user specific and not application specific), when you can simply get it from this object:
HttpContext.Current.User
check this one for details: How to get current user who's accessing an ASP.NET application?

You can get the user identity (if you're using asp.net forms membership) through:
HttpContext.Current.User.Identity.Name

On logging in, if the user is valid, use:
FormsAuthentication.SetAuthCookie(login.UserName, false);
rather than relying on Session to store user logged in state.
You can then check if a user is logged in by:
User.Identity.IsAuthenticated
And get their username doing:
User.Identity.Name

You can just simply use
User.Identity.Name

You can use User.Identity.Name
Please have a look at HttpContext.User Property

Related

Cookies in ASP.Net MVC 5

I am developing an application in which users are SignUp or SignIn by External Identity Providers like AAD, Google, WS-Federated Authentication etc. Now I want to create cookies on a user machine to logged in until user SignOut. Give me some thought and guide me how I can overcome it. thanks in advance.
Use Request.Cookies and Response.Cookies to handle your situation. once user coming back from third party authorization create cookie and store it in browser and once user Logout clear the cookie.
string cookievalue ;
if ( Request.Cookies["cookie"] != null )
{
cookievalue = Request.Cookies["cookie"].Value.ToString();
}
else
{
Response.Cookies["cookie"].Value = "cookie value";
}
For removing cookie use following code
if (Request.Cookies["cookie"] != null)
{
Response.Cookies["cookie"].Expires = DateTime.Now.AddDays(-1);
}

Verify newly entered password of logged in user

User is logged in and wants to do something major and I want them to re-enter their password so I can make sure that they are the user that is logged in.
How can I confirm that this password is for the account holder?
Would be happy to know how to do it via ASP.NET Identity or how to set up a stored proc to go against the AspNetUsers table or how to do it via Entity Framework.
How can I confirm that this password is for the account holder?
how to do it via ASP.NET Identity
To reverify the password of currently logged in user, provide the user VerifyView to enter password and use the following method to check if the user exists.
var user = await UserManager.FindAsync(User.Identity.Name,VerifyViewModel.Password)
If the user is found, the current request is the same from the account holder.
Membership.ValidateUser is from earlier version of Membership framework, not from ASP.NET Identity.
You can also use UserManager.CheckPassword() extension function:
UserManagerExtensions.CheckPassword Method
string id = User.Identity.GetUserId();
var user = UserManager.FindById(id);
if(!UserManager.CheckPassword(user, model.Password))
{
ModelState.AddModelError("Password", "Incorrect password.");
}
With Identity framework you never want to hit the database directly. Always use the API provided. The database structure has changed several times in the past few years, so introducing dependencies (e.g. on a data context) is adding work for no reason.
For async usage, see the answer already provided by jd4u.
For synchronously identifying that the password matches the current user, you need to first include:
using Microsoft.AspNet.Identity;
as this brings in a number of synchronous extension methods for identity framework.
You can then check with Find on the UserManager like this:
var user = UserManager.Find(User.Identity.Name, password);
if (user != null)
{
// It is them!
}
If the user is not null, then you have a match of password and current username.
You can use UserManager to do that:
if(UserManager.PasswordHasher.VerifyHashedPassword("hashedPassword", "password")
!= PasswordVerificationResult.Failed)
{
// password is correct
}
For more information see the link:
How to check password manually in Asp.Net identity 2?

Best practice to check data of a user before logging in

There is a table that keeps a user's details. An admin can lock this user by setting the column called locked. Once the user is locked they cannot login. I am using The WebSecurity.Login to login. As of now I am letting the user to login, then it checks if they are not locked and if they are instead of home page they are redirected to locked page.
What is the best practice that I can use so that the user doesnt gets logged in, check the field and gets redirected. This is in MVC 4
Thanks in advance...
Maybe I misunderstand you.. but currently you have something like this:
Membership.LoginUser(userName, password);
if (CurrentUser.IsLocked) {
RedirectUser();
}
..can you not just replace it with something like this?:
var user = Membership.GetUser(userName, password);
if (user.IsLocked) {
Redirect();
}
else {
Membership.LoginUser(user);
}
... ?

How to lock user using forms authentication

Coding Platform: ASP.NET 4.0 Webforms with C#
I have two roles admin and member.
In my application, admin can manipulate most of the member data.
I know that in forms authentication a user can be unlocked like,
MembershipUser user = Membership.GetUser(clickeduserName);
user.UnlockUser();
Membership.UpdateUser(user);
My questions are,
How to lock a user in forms authentication?
Why is MembershipUser.IsLockedOut
Property set as ReadOnly?
Is it not the right way to LockOut
people as an administrator?
There are a few options discussed here: http://forums.asp.net/t/1435151.aspx
They vary from using IsApproved (settable) instead of IsLockedOut to mucking with the underlying SQL database to set the lockout flag.
You can make it lock the user (set .IsLockedOut to true) by doing the following:
MembershipUser user = Membership.GetUser("UserToLock");
for (int i = 0; i < Membership.MaxInvalidPasswordAttempts; i++)
{
Membership.ValidateUser(user.UserName, "Not the right password");
}
Excerpt from MSDN:
Normally, User's are LockedOut automatically when the MaxInvalidPasswordAttempts is reached within the PasswordAttemptWindow.
Users can also be locked out if you use the GetPassword or ResetPassword overload that accepts a password answer and the number of bad answers entered by the user reaches the value of Membership.MaxInvalidPasswordAttempts within the Membership.PasswordAttemptWindow.
A workaround could be to use IsApproved property like this:
MembershipUser user = Membership.GetUser();
user.IsApproved = false;
Membership.UpdateUser(user);

SPFile.CheckoutBy gives System/account instead of my login

Description: i am user user1 (which is also the user of the app pool of sharepoint, so when i logon with user user1 it says welcome system account).
In my code, i want to test if a file is checked out by user 1, so the result of the following:
file.CheckedOutBy.LoginName.ToLower() == userName.ToLower())
is always false (which is not correct), CheckOutby value is (Sharepoint system) while username value is (user1).
How to resolve this?
Im using SP2010
You shouldn't use the user account which is used as a app pool account, because You will always see system account. In this case the best way is to change the app pool account to another which won't be used for another purposes.
Where does username come from?
Try this:
SPWeb web = SPContext.Current.Web; //get it from somewhere
if(file.CheckedOutBy == web.EnsureUser(username)) {
//do something
}
That should do the comparison on the SPUser.Id
Thanks all, this is how i solved it:
file.CheckedOutBy.LoginName.ToLower() == web.CurrentUser.LoginName.ToLower()
giving sharepoint\system on both sides, which was corrected.

Categories

Resources