Saving username and password for future sessions - c#

I have a application where to access the database user has to be in a session. When the user logs in, in browser he/she gets authenticated and session starts. Here is an example
[HttpPost]
[AllowAnonymous]
public ActionResult CustomLogin(LoginModel login)
{
using (var loginsSession = SoSession.Authenticate(login.Username, login.Password))
{
var x = 0;
}
return null;
}
Problem
Everytime user gets out of this controller's login function, the session expires.
If the user wants to access database again, I need to create new session but the problem is I don't know how to store the username and password so that I don't have to ask user to login again and again.
Is there some smart way to store username and password somewhere so that I can use it till the user logs out from the browser?

I'm not sure: You are using session in using (){} statement. When you get out of login controller, The using statement calls the Dispose method on the Session.
Hope this help.

Related

How to login user after creating it

I have the following method to create a new user in Azure Active Directory using the Graph API:
public static async Task AddUserAsync(User user)
{
Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient adClient =
GetActiveDirectoryClient();
await adClient.Users.AddUserAsync(user);
}
After the user is created using this method, I need to automatically log the user in.
I'm looking for something like the SignInManager.SignInAsync or SignInManager.PasswordSignInAsync methods.
To add to #David answer, when redirecting to Azure AD after creating the user you can specify login_hint=user#domain.com. This auto-fills the username in the login page.
If you want them "really" logged in with AAD, you'll need to log the current user out and send them back to the login page so that they get sent through the Microsoft login process.
If you don't want to do this, you could probably create a user object manually that you could pass to SignInManager.SignInAsync.

Avoid session id reuse asp.net

I am using cookie based session by using FormsAuthentication.SetAuthCookie.
Is there an easy go so that I can set the reuse of expired sessionId and each time when the session expires ASP.NET creates a new session id.
Thanks.
You have to deal with a couple of different cases. The first is when someone clicks on the logout button. The second is when the session itself has expired (but no user action has occured).
In the second instance, forms authentication will automatically send you to the login page that you have defined in your web.config.
You could do something like the following
[AllowAnonymous]
public ActionResult Login()
{
Response.Cookies.Add(CreateExpiredBlankCookie("ASP.NET_SessionId"));
return View();
}
private HttpCookie CreateExpiredBlankCookie(string name)
{
var cookie = new HttpCookie(name, "");
cookie.Expires = DateTime.Now.AddDays(-1);
return cookie;
}
You can use Session.Abandon() to prevent session reuse.
Because HTTP is stateless, there's no way you can know when the user has closed the browser. But, you can put a logout button on every page and as part of your handling for the button, call Session.Abandon to prevent a third-party from reusing it.
Beyond that, require HTTPS and make sure your cookies also require HTTPS.

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);
}
... ?

Log In User with Parameters when Changing Password

I have an ASP.NET App in which want to send an email to a user that presses a Recover Password button that resets the user's password and then sends a link to the user that when followed will log the user in with a new password and bring them to the Change Password page where they must resent their password.
I'm able to reset the password and get the new randomly generated password that I send back to the user in an email. However, when the user follows the link back with the UserName and pw parameters, the system does not seem to log them in,
Here's the code I am using on the load event that does not seem to work:
try
{
string sUserName = Request.QueryString["UserName"].ToString();
string sPw = Request.QueryString["pw"].ToString();
if (Membership.ValidateUser(sUserName, sPw))
{
//Log the user in???
FormsAuthentication.Authenticate(sUserName, sPw);
}
}
catch (Exception r)
{
string sMessage = r.Message;
}
Any help in logging the user in with username and password parameters would be greatly appreciated.
You can use FormsAuthentication.SetAuthCookie() :
if (Membership.ValidateUser(sUserName, sPw))
{
FormsAuthentication.SetAuthCookie(sUserName, true);
}
In your sample code you are retrieving the user name and password from the query string - this is very bad practice as any observer will see it in plain text. At least use a POST for these values and put them in the body (i.e with a form POST) and always use HTTPS at least for your login page.
use the following code.
if (Membership.ValidateUser(sUserName, sPw))
{
FormsAuthentication.SetAuthCookie(sUserName, true);
Response.Redirect("ChangePassword.aspx");
}
FormsAuthentication.Authenticate is almost same as FormsAuthentication.ValidateUser. They just validate user authentication. SetAuthCookie creates the authentication ticket(login).
This is how (IMO) reset password functionality should work:
User clicks button saying "Forgot Password".
In your code store a random GUID in the DB.
Send the user an email, with the GUID as a link in the email, as well as their userid, e.g:
http://yoursite.com/user/reset?guid=a21312738&userid=213123
On the incoming page, read the userid from the QS, and fetch the user from the DB by this value.
Compare the stored GUID from the GUID in the QS. If success, render a form that allows the user to change the password via an HTTPS POST.
In the POST action, change the user's password and sign them in.
You could also go one step further and store an expiration date for the GUID (e.g user must change their password in 24 hours).

How to log off multiple MembershipUsers that are not the current user?

I'm using the MembershipProvider that is part of the MVC2 default project.
I'd like to be able to take a list of user names, and log the users off, and destroy their session if needed. The closest I can seem to come is this:
foreach(string userName in UserNames)
{
MembershipProvider MembershipProvider = new MembershipProvider();
MembershipUser membershipUser = MembershipProvider.GetUser(userName, true);
Session.Abandon();
FormsAuthentication.SignOut();
}
I think I need to use a session and/or signout method related the user I want to log out, but I am unsure where those would be.
What is the proper way to do this?
That won't work...
Session.Abandon() will be for the Current HttpContext. Not for each user like you are trying to do.
Same for FormsAuthentication.SignOut().
Your best bet is check the current user against that array in the Application_AuthenticateRequest Event and sign them out there:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
//add your ckeck here
if (Usernames.Contains(User.Identity.Name))
{
Session.Abandon();
FormsAuthentication.SignOut();
}
}
}
I Didn't use the Membership provider when i did this but basically i saved the SessionId, Username and lastPage visited in a database when the user logged on. Each page then used the current SessionID to get the username and do related username stuff, like display balance for current user etc. if there isn't a valid user for the session then return to log-on page.
This allowed me the see the users progress through the website and manually disconnect whoever i wanted and gave me Single Signon per user . There was also a bunch of clean-up code in the global.asx page
This turned out to not be related so much to the MembershipProvider, but to the FormsService. My final solution turned out to be a sort of hybrid of the two other answers posted here.
I ended up creating my own FormsAuthenticationTicket in the Account controller in the LogOn action. I generate a unique identifier for the user's authenticated session, and save that identifier to the database. I also added the user's ID to the UserData part of the auth ticket for reliable lookup. By default the auth ticket only contained their user name. The FormsAuthenticationTicket is then stored in a cookie upon successful user log on.
Basically all of that replaced the FormsService.SignIn(model.UserName, model.RememberMe);
I also added public void Application_ReleaseRequestState(object sender, EventArgs args) in the Global.asax. I'm not sure if this is considered expanding a function or what, as it does not appear to be an override. Inside of Application_ReleaseRequestState it gets the user's FormsAuthenticationTicket from a cookie. It then decrypts the auth ticket, and gets the user's UserID from the UserData portion of the ticket. Then it asks the database if the auth ticket is still valid. If the ticket is not valid, it sets the user's cookie to expire.
To force users to log off, I can either change their auth ticket expiration dates in the database, or toggle the disable bit for their auth tickets in the database. Either way when Application_ReleaseRequestState asks the database if their auth tickets are valid, they won't be. Thus their cookies will get set to expire upon the next page the user hits after this check was made.

Categories

Resources