Expireing active registration link in asp.net - asp.net

As a user register in my website, a registration link will send him. What i want is to expire this link after 48 hours. Is there any way to do that?
Thank you so much.
here is my codes:
In activate page:
string userID = Request.QueryString["userID"];
Guid gd = new Guid(userID);
Membership.UpdateUser(user);
In activate page:
MembershipUser user = Membership.CreateUser(TextBox_email.Text, TextBox_Pass.Text, TextBox_email.Text);
Roles.AddUserToRole(TextBox_email.Text, "Author");
user.IsApproved = false;
Membership.UpdateUser(user);
// StringBuilder bodyMsg = new StringBuilder();
Guid userID = (Guid)user.ProviderUserKey;

I guess this is all about special querystring/route parameters in your activation link
You can, for example :
store a link identifier and the date it has been issued in a datastore/database. Then check that a user link is no more than 48h old when a user accesses your site with it.
store a timestamp in the link itself (no need of a db), as well as a hashcode of the timestamp concatenated to a secret key of yours. When a user comes with a link, verify that the hashcode and the timestamp match, then verify that the timestamp is no more than 48h old

Related

How to get IdentityUser by Username

I have previously worked with Membership through "System.Web.Security.Membership"
Here, you can do the following:
var currentUser = Membership.GetUser();
var otherUser = Membership.GetUser(username);
...giving you a MembershipUser.
Now, with Identity, I can find a load of ways to get the current logged in user.
But no way to get another user.
I can use:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = userManager.Find(username, password);
But that takes both username and password, with no overload for just username.
How do i get the IdentityUser from only a username?
Almost every answer I find is connected to MVC.
This is for a WCF service, where authorization is made using Identity. And in some cases the user is getting to the site from an other site with a generated "token" - an encrypted string, containing the username. From here, user is logged in and a session-cookie is set, depending on users settings.
Also, is there a shorter way to get UserInformation?
"var currentUser = Membership.GetUser(username);"
is much more convenient than
"var user2 = (new UserManager((new UserStore()))).Find(username, password);"
UserManager has UserManager<TUser>.FindByNameAsync method. You can try using it to find user by name.

MVC 5 - change password on demo accounts

I have an MVC 5 demo application that uses asp.net security. Within that application I have 75+ user accounts.
The person who gives the demos left, so I'd like to be able to reset all of the passwords for all of the accounts without having to change the email on each account to my personal email and do them individually where a link would be sent to my personal email.
Is there a way I can type in the user name and new password and use built in IdentityUser functionality to reset the password?
Assuming your app is in standard MVC5 format, put this ViewResult into the Account controller:
[AllowAnonymous]
public async Task<ViewResult> ResetAllPasswords()
{
// Get a list of all Users
List<ApplicationUser> allUsers = await db.Users.ToListAsync();
// NOTE: make sure this password complies with the password requirements set up in Identity.Config
string newPassword = "YourNewPassword!";
int passwordChangeSuccess = 0;
int countUsers = 0;
// Loop through the list of Users
foreach (var user in allUsers)
{
// Get the User
ApplicationUser thisUser = await UserManager.FindByNameAsync(user.UserName);
// Generate a password reset token
string token = await UserManager.GeneratePasswordResetTokenAsync(thisUser.Id);
// Change the password, using the reset token
IdentityResult result = await UserManager.ResetPasswordAsync(thisUser.Id, token, newPassword);
// Record results (extend to taste)
if (result.Succeeded)
{
passwordChangeSuccess++;
}
countUsers++;
}
ViewBag.CountUsers = countUsers;
ViewBag.PasswordSuccess = passwordChangeSuccess;
return View();
}
and set up a new View with ViewBag.CountUsers and ViewBag.PasswordSuccess to check the results.
Then set up an ActionLink pointing to ResetAllPasswords in Account controller and press to go.
Obviously the formatting can be changed (maybe a form with a confirm instead, maybe with an input field to specify the password .. ), but the basic controller code should hopefully be good. And note the [AllowAnonymous] attribute is there just for one-off access - not a good idea to leave it there for anything more than testing!
This should reset all Users to the same password specified in the code.
yes in Account Controller just go to the forget Password function and change that code a little where first of all user search the email id and after that system send a mail to that user .
There just write down a code where user send mail to your specific email id then you can get that link in your account click that link and reset the Password

Logout User From all Browser When Password is changed

I have a Reset Password page:
When the user fills the details and clicks the Reset Password button. The following controller is called:
public ActionResult ResetPassword(ResetPassword model)
{
...
return RedirectToAction("Logout");
}
When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they remain logged in on the other browser.
I want to log out the user from all browsers they are logged into when they change their password.
I saw you are using ASP.NET Identity 2. What you are trying to do is already built in. All you need to do is change the SecurityStamp and all previous authentication cookies are no longer valid.
After you change the password you also need to change the SecurityStamp:
await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
await UserManager.UpdateSecurityStampAsync(User.Identity.GetUserId());
If you want the user to remain logged in, you have to reissue a new authentication cookie (signin):
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
Otherwise the user/session who initated the password change will also be logged out.
And to log out all other sessions immediately you need to lower the check interval in the config:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromSeconds(1),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Steps to reproduce:
Created a new Asp.Net Web App in VS2015.
Choose MVC template.
Edit App_Stat/Startup.Auth.cs, line 34: change validateInterval: TimeSpan.FromMinutes(30) to validateInterval: TimeSpan.FromSeconds(1)
Edit Controllers/ManageController.cs, line 236: add the UserManager.UpdateSecurityStampAsync method call.
Run project, create a user, login, open a different browser and also login.
Change password, refresh the page in the other browser : you should be logged out.
So I got home and decided to put together some code. Show me the code !!!
I would use a handler so the verification is always done when the user first access the application and it is done at one place for every action method access.
The idea is when the user reset their password, the application records the user has reset their password and have not logged in for the first time and sign out the user.
user.HasResetPassword = true;
user.IsFirstLoginAfterPasswordReset = false;
When the user signs in, the application verifies if the user had previously reset their password and is now signing in for the first time. If these statements are valid the application updates its records to say you have not reset your password and you are not signing in for the first time.
Step 1
Add two properties to ApplicationUser model
Step 2
Add a class AuthHandler.cs in Models folder with the implementation below.
At this stage you verify if the user has reset their password and has not logged in for the first time since the password was reset. If this is true, redirect the user to the login.
Step 3
In RouteConfig.cs call the AuthHandler so that it is invoked for each incoming http request to your application.
Step 4
In ResetPassword method add implementation as below. At this step when a user has reset their password update the properties to say , they have reset their password and have not logged in for the first time. Notice the user is also signed out explicitly when they reset their password.
Step 5
In Login method add the implementation below. At this step if a user logins in successfully, verify their password was reset and they has logged for the first time is false. If all the conditions are true, update the properties in the database, so the properties are in a state ready for when the user resets the password in the future. So kind of a loop determining and updating the state of the password reset and first logins after resetting the password.
Lastly
Your AspnetUsers table should look as below
Comments
This is how I would approach it. I have not tested it so you may have modify it if you encounter exception. It is all also hard coded to show the approach to solved the problem.
Even ASP.NET Authentication says clearly that you have to have a secondary check to confirm if user is still an active logged in user (for example, we could block the user, user may have changed his password), Forms Authentication ticket does not offer any security against these things.
UserSession has nothing to do with ASP.NET MVC Session, it is just a name here
The solution I have implemented is,
Create a UserSessions table in the database with UserSessionID (PK, Identity) UserID (FK) DateCreated, DateUpdated
FormsAuthenticationTicket has a field called UserData, you can save UserSessionID in it.
When User Logs in
public void DoLogin(){
// do not call this ...
// FormsAuthentication.SetAuthCookie(....
DateTime dateIssued = DateTime.UtcNow;
var sessionID = db.CreateSession(UserID);
var ticket = new FormsAuthenticationTicket(
userName,
dateIssued,
dateIssued.Add(FormsAuthentication.Timeout),
iSpersistent,
// userData
sessionID.ToString());
HttpCookie cookie = new HttpCookie(
FormsAuthentication.CookieName,
FormsAuthentication.Encrypt(ticket));
cookie.Expires = ticket.Expires;
if(FormsAuthentication.CookieDomain!=null)
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.CookiePath;
Response.Cookies.Add(cookie);
}
To Authorize User
Global.asax class enables to hook into Authorize
public void Application_Authorize(object sender, EventArgs e){
var user = Context.User;
if(user == null)
return;
FormsIdentity formsIdentity = user.Identity as FormsIdentity;
long userSessionID = long.Parse(formsIdentity.UserData);
string cacheKey = "US-" + userSessionID;
// caching to improve performance
object result = HttpRuntime.Cache[cacheKey];
if(result!=null){
// if we had cached that user is alright, we return..
return;
}
// hit the database and check if session is alright
// If user has logged out, then all UserSessions should have been
// deleted for this user
UserSession session = db.UserSessions
.FirstOrDefault(x=>x.UserSessionID == userSessionID);
if(session != null){
// update session and mark last date
// this helps you in tracking and you
// can also delete sessions which were not
// updated since long time...
session.DateUpdated = DateTime.UtcNow;
db.SaveChanges();
// ok user is good to login
HttpRuntime.Cache.Add(cacheKey, "OK",
// set expiration for 5 mins
DateTime.UtcNow.AddMinutes(5)..)
// I am setting cache for 5 mins to avoid
// hitting database for all session validation
return;
}
// ok validation is wrong....
throw new UnauthorizedException("Access denied");
}
When User Logs out
public void Logout(){
// get the ticket..
FormsIdentity f = Context.User.Identity as FormsIdentity;
long sessionID = long.Parse(f.UserData);
// this will prevent cookie hijacking
var session = db.UserSessions.First(x=>x.UserSessionID = sessionID);
db.UserSession.Remove(session);
db.SaveChanges();
FormsAuthentication.Signout();
}
When user changes password or user is blocked or user is deleted...
public void ChangePassword(){
// get the ticket..
FormsIdentity f = Context.User.Identity as FormsIdentity;
long sessionID = long.Parse(f.UserData);
// deleting Session will prevent all saved tickets from
// logging in
db.Database.ExecuteSql(
"DELETE FROM UerSessions WHERE UserSessionID=#SID",
new SqlParameter("#SID", sessionID));
}
The ASP.NET Identity authentication is dependent on cookies on the user's browser. Because you use two different browsers to test it. You will have two different authentication cookies.Until the cookies expire the user is still authenticated That is why you are getting that results.
So you will have to come with some custom implementation.
For instance, always check if the user's has reset the password and has not yet logged in for the first time with the new password. If they haven't, logout them out and redirect to login. When they login a new auth cookie will be created.
I modeled my approach around this article from Github's Blogs
Modeling your App's User Session
They use a Hybrid Cookie Store / DB approach using ruby but I ported it to My ASP .Net MVC project and works fine.
Users can see all other sessions and revoke them if needed. When a user resets password, any active sessions are revoked.
I use an ActionFilterAttribute on a base controller to check active sessions cookies. If session cookie is found to be stale the user is logged out and redirected to sign in.
Based on CodeRealm's answer...
For anyone who experiences a situation where https access to your application on the browser throws a null pointer exception (i.e Object reference not set to an instance of an object.), it is because there might be existing records in your database where HasResetPassWord and/or IsFirstLoginAfterPasswordReset is null. Http requests will work, but https requests will fail, not sure why.
Solution: Just update the database manually and give both fields values. Preferably, false on both columns.

I can't read cookies in master or other pages

I create some cookies in logon.aspx.cscodebehind thatc read and contain user info from DB with data reader .
HttpCookie UID = new HttpCookie("ID");
Response.Cookies["UID"].Value = Recordset[0].ToString();
Response.Cookies.Add(UID);
HttpCookie UName = new HttpCookie("Username");
Response.Cookies["Username"].Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
HttpCookie Pass = new HttpCookie("Pass");
Response.Cookies["Pass"].Value = Recordset[4].ToString();
Response.Cookies.Add(Pass);
HttpCookie Admins = new HttpCookie("Admin");
Response.Cookies["Admin"].Value = Recordset[12].ToString();
Response.Cookies.Add(Admins);
HttpCookie Mails = new HttpCookie("Emails");
Response.Cookies["Emails"].Value = Recordset[9].ToString();
Response.Cookies.Add(Mails);
Response.Redirect("../default.aspx");
when i trace the code every thing is good and data hold by cookies.
Now when i read these cookies in master page or other content page, i can't.
in other worlds the cookies not recognize by their names(or keys)
if (Request.Cookies["Username"] !=null)
{
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
pnlUsersNavigation.Visible = true;
LoginMenu.Visible = false;
RegisterMenu.Visible = false;
lblWelcomeUser.Text = Server.HtmlEncode(Request.Cookies["Username"].Value);
//lblWelcomeUser.Text = Request.Cookies["Username"].Value.ToString();
if (Request.Cookies["Admin"].Value.ToString()=="True")
{
lblWelcomeUser.Text = "WELCOME ADMIN";
// Show Menu that is only for Admin
}
where is the problem in this code?
It appears that you might be overwriting the cookie with a good value, with a new empty cookie.
// new cookie created - empty
HttpCookie UName = new HttpCookie("Username");
// new cookie created with a value
Response.Cookies["Username"].Value = Recordset[3].ToString();
// overwrite new cookie with value with new empty cookie
Response.Cookies.Add(UName);
Create the cookie, set the value, then add the cookie to the response.
HttpCookie UName = new HttpCookie("Username");
UName.Value = Recordset[3].ToString();
Response.Cookies.Add(UName);
Also note that as Paul Grimshaw pointed out, you can add multiple values to the same cookie.
Download Fiddler to check request/response to ensure your cookies contain the correct values and such... http://fiddler2.com/get-fiddler
Also be careful about Man-in-the-middle attacks. Storing usernames and passwords in plain text is not such a good idea to begin with.
This doesn't look like a very secure way of securing access to your application. Try looking at ASP.NET membership.
Otherwise try setting an expiry date. Also, as this example shows, you may want to store all the above info in one cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["UID"] = Recordset[0].ToString();
myCookie["Username"] = Recordset[3].ToString();
//...etc...
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
Also, from MSDN:
By default, cookies are shared by all pages that are in the same
domain, but you can limit cookies to specific subfolders in a Web site
by setting their Path property. To allow a cookie to be retrieved by
all pages in all folders of your application, set it from a page that
is in the root folder of your application and do not set the Path
property. If you do not specify an expiration limit for the cookie,
the cookie is not persisted to the client computer and it expires when
the user session expires. Cookies can store values only of type
String. You must convert any non-string values to strings before you
can store them in a cookie. For many data types, calling the ToString
method is sufficient. For more information, see the ToString method
for the data type you wish to persist.

Are there any unique Id for every user connects to my web server?

I need a unique ID for every user connects to my Web server(web site).
How can I earn it?
You can use SessionID property. It is unique for each user.
Use GUid and store it in session:
string id =
System.Guid.NewGuid().ToString();
Session["id"] = id;
Depending on your requirements, you could generate your own unique ids, and store them in cookies.
It depends on whether you want a Session ID or a User Id.
If you want the Id to be retained for a given User, then you need to create a permanent cookie for that user. I'd suggest using the Application_BeginRequest method in Global.asax, check the Request cookies - if they have the cookie you created then extract the Id - otherwise create a new one using the Guid class:
if(HttpContext.Current.Request.Cookies["MyCookie"] == null)
{
HttpCookie newCookie = new HttpCookie("MyCookie");
newCookie .Values["Id"] = System.Guid.NewGuid().ToString();
HttpContext.Current.Response.Cookies.Add(newCookie);
}

Resources