why login page in asp.net mvc loads very slow? - asp.net-mvc

this is my controller
#region Authentication
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(string username, string password)
{
// Lets first check if the Model is valid or not
if (ModelState.IsValid)
{
bool userValid = itreedb.Users.Any(user => user.UserName == username && user.Password == password && user.Approved == true);
// User found in the database
if (userValid)
{
//
// Save un and pw into cookies
HttpCookie auth = new HttpCookie("auth", Request.Form["username"] + "|" + Request.Form["password"]);
auth.Expires.AddDays(30);
Response.Cookies.Add(auth);
// Redirect the user to the index page
return Json(new { IsValidLogin = true });
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View();
}
When I try to insert my admin informations it takes more than 5 minutes to be authentified .The others pages reload normally. What can I do?
`

Related

How to permanently pass a value to view until user closes browser? MVC

When welcome page gets refreshed the value i tempData gets Lost. I have applied a check on user login (admin login) and hide / show an element accordingly. For example if user type is 1 (global admin) is shows 'admin management' link on welcome page otherwise it hides it. I am working with tempData to store the 'Type' it works as expected on login but if I refresh Welcome page it raises this error: Please Help
My Logic
public ActionResult Login()
{
ViewBag.Message = "Your Login page.";
return View();
}
[HttpPost]
public ActionResult Login(tbl_Admin adminObj)
{
studentDBEntities db = new studentDBEntities();
var adminvar = db.tbl_Admin.Where(x => x.Email == adminObj.Email && x.Password == adminObj.Password).FirstOrDefault();
if (adminvar != null)
{
if (adminvar.Type== true)
{
TempData["IsGlobalAdmin"] = true;
return RedirectToAction("Welcome");
}
else
{
TempData["IsGlobalAdmin"] = false;
return RedirectToAction("Welcome");
}
}
else
{
return View();
}
}
public ActionResult Welcome()
{
ViewBag.Message = "Welcome Admin - Admin Account Page";
return View();
}
my view
#model IEnumerable<StudentReg.tbl_Admin>
<div class="well">
<center><h4><b>Navigate To: </b></h4></center>
#if ((bool)TempData["IsGlobalAdmin"])
{
<center><p>#Html.ActionLink("Admin Management", "ListAdmin")</p></center>
}
<center><p>#Html.ActionLink("Student Management", "ListStudent")</p></center>
</div>

ASP.NET MVC 5 - let admin change other users password. Password changed in database but can't login

I'm told to make admin have a functionality to change other users password without knowing their original password. I wrote a code that changes and saves password successfully in database, but when I try to login as that user I can't.
UsersController:
public ActionResult ChangePassword()
{
return View();
}
[HttpPost]
public ActionResult ChangePassword(int id, ViewModels.ChangePasswordViewModel model)
{
if (!SessionControlService.CheckIsLoginStillTrue(_loginsService, HttpContext))
return RedirectToAction("Login", "Account");
if (!User.IsInAnyRoles("Admin", "PropertyManager"))
return RedirectToAction("Error", "Errors",
new { error = Facility.Web.Resources.Resources.ErrorNotHavePermission });
var user = _userService.GetUser(id);
if (user == null)
return RedirectToAction("Error", "Errors",
new { error = Facility.Web.Resources.Resources.ErrorURLNotExist });
user.Password = model.NewPassword;
_userService.UpdateUser(user);
return RedirectToAction("Details", new { id = id });
}
Why can't I use the changed password which is saved in the database to login?
How can I make this work?
In ASP.NET MVC5, password is hashed... you cannot save a plaintext password like that.
You need to use these two methods:
var manager = new ApplicationUserManager(...);
var token = manager.GeneratePasswordResetToken(userId)
manager.ResetPassword(userId, token, newPassword)
You could also try ApplicationUserManager.UpdatePassword(...), or RemovePassword(...) and AddPassword(...)
ApplicationUserManager is normally in IdentityConfig.cs

MVC 5 Identity Login and "Remember Me" - What needs to be done to get it set up?

I have the following code in my Account controller:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
ApplicationUser user = null;
// In order to authenticate, we need a user name. Let's find it based on the email address.
user = await this.UserManager.FindByEmailAsync(model.Email);
if (user != null)
user = await this.UserManager.FindAsync(user.UserName, model.Password);
if (user != null && user.EmailConfirmed)
{
await this.SignInAsync(user, model.RememberMe);
return this.RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Either your username or password is invalid, or your email address has not yet been confirmed");
}
}
// If we got this far, something failed, redisplay form
return this.View(model);
}
It appears that "Remember Me" is already being handled with this snippet of code:
if (user != null && user.EmailConfirmed)
{
await this.SignInAsync(user, model.RememberMe);
return this.RedirectToLocal(returnUrl);
}
However, it doesn't seem to be working reliably. Is there anything else that needs to be done to set up "Remember Me?"
you can use this code
FormsAuthentication.SetAuthCookie(user.UserName, model.RememberMe);

Redirect to actionmethod/view

I have implemented idel time out functionality. Here when the user is idel for 1 min, we redirect the user to login page. We have kept the track of the url that the user was when the auto logout happened. Eg , of the user is on reset password view and if the auto logout happens the url which i get is as follows
http://localhost/XYZ.Portal/?returnUrl=%2FXYZ.Portal%2FUser%2FResetPassword
the above url is achieved by using the following code
'#Url.Action("Login", "User", new { returnUrl = HttpContext.Current.Request.RawUrl })'
Now when the user logs in again as he is redirected to login page, I am using the following code to redirect him back but the code doesnt seem to work. What am I doing wrong.?
[HttpPost]
public ActionResult Login(FormCollection formCollection)
{
if (ModelState.IsValid)
{
UserBE user = new UserBE();
user.Email = formCollection["Email"];
user.Password = formCollection["Password"];
user = UserBL.AuthenticateUser(user);
if (user.AuthenticUser)
{
if (Request.QueryString["returnUrl"] != null)
{
string returnUrl = Server.UrlDecode(Request.QueryString["returnUrl"]);
Redirect(returnUrl );
}
else
{
Session["Email"] = user.Email;
return RedirectToAction("DashBoard");
}
}
else
return View(user);
}
return View();
}
[HttpGet] login action method:
[HttpGet]
public ActionResult Login()
{
return View();
}
returnUrl I get as XYZ.Portal/User/ResetPassword
Thanks In advance.
You need to return the RedirectResult:
if (Request.QueryString["returnUrl"] != null)
{
string returnUrl = Server.UrlDecode(Request.QueryString["returnUrl"]);
return Redirect(returnUrl);
}
See RedirectResult
Not working. Now my URL becomes localhost/XYZ.Portal
In this case you can do 1 of 2 options:
1) Write:
string startReturnUrl = "http://www." + your returnUrl
or
2) split your returnUrl like:
string viewName = returnUrl.Split('/').Last();
But I think better change returnUrl to just only Name of View that you need

Custom login with mvc messing up with the login partial view

So I've set up a custom login in my MVC application which appears to work...
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Login())
{
FormsAuthentication.SetAuthCookie(model.Username, true);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Invalid email address or password.");
}
}
// If execution got this far, something failed, redisplay form
return View(model);
}
public class User
{
public bool Login()
{
var user = db.Users.FirstOrDefault(u => u.EmailAddress == EmailAddress);
if (user == null)
{
throw new ValidationException("User not found.");
}
else
{
// validates whether or not the password on the user record
// that was retrieved by the query matches the password entered at login
return Hashing.ValidatePassword(Password, user.Password);
}
}
}
Unfortunately, there's some conflict between it and the default _LoginPartial.cshtml View (which looks like below):
#model LoganMVC.Models.User
#if (Request.IsAuthenticated) {
<text>
Hello, #Html.ActionLink(User.Identity.Name, "Manage", "Account", new { User.Identity.Name })!
#using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) {
#Html.AntiForgeryToken()
Log off
}
</text>
} else {
<ul>
<li>#Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>#Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
The ArgumentNullException highlights this line...
Hello, #Html.ActionLink(User.Identity.Name, "Manage", "Account", new { User.Identity.Name })!
Saying...
Value cannot be null or empty.
It's clear that the value that cannot be null or empty is User.Identity.Name, but what isn't clear is WHY IsAuthenticated is true to begin with. This is Forms Authentication and, as far as the software is aware (because I killed the debug server, closed the solution and started debugging fresh again), the application has never run before.
Okay I've been bashing my head against various hard surfaces trying to get this one figured out and eventually did.
After looking at the errors I was initially getting:
Value cannot be null or empty.
And then later
The provided identity of type 'System.Web.Security.FormsIdentity' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user.
Were fairly simple fixes.
First off, I had initially set my login cookie to persist. This means that it wouldn't be deleted when the browser is closed and would not expire either. While this did not cause the Value cannot be null or empty error, it was contributory in that the site was finding it and assuming a user had authenticated.
FIX
To fix this, I simply cleared cookies from my browser set the cookie's persist to false. This allowed me to focus more on the actual problem.
Value cannot be null or empty
This problem was actually not as complicated as I thought. When I started taking a closer look at things, I noticed that there was an error in the following code:
[HttpPost]
public ActionResult Login(User model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Login())
{
FormsAuthentication.SetAuthCookie(model.Username, true);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Invalid email address or password.");
}
}
// If execution got this far, something failed, redisplay form
return View(model);
}
This post captures an instance of my User model from the form (which is the login form so only EmailAddress and Password values are included). It also uses the Username value from this model (which is null) to set the Authentication Cookie.
I changed my .Login() method to a function that returns a User if the email address is found and the stored hash matches a hash of the password entered for the login.
The code, thus, changed to the following (this is only the key point of the change)
// Account.Login Post
if (ModelState.IsValid)
{
var user = model.Login(model.EmailAddress);
if (user == null)
{
ModelState.AddModelError("", "Invalid email address or password.");
}
FormsAuthentication.SetAuthCookie(user.Username, true);
// create session variables n such
}
// User.Login
public User Login(string EmailAddress
{
var user = dbContext.Users.FirstOrDefault(u => u.EmailAddress == Email);
if (user == null)
throw new Exception("User not found.");
if (Hashing.ValidatePassword(Password, user.Password))
return user;
return null; // if we got here, something went wrong
}
Once I'd fixed this, I got another problem later. Some issue to do with the Anti-Forgery system.
While not a solution, I managed a workaround and commented out the following line from my _LoginPartial View:
#Html.AntiForgeryToken()
I had concerns about security but I figured that Forms Auth on a basic asp.net website with a hashed and salted password has been sufficient for quite a number of years, so I shouldn't have any issues with it here.
You probably miss something. In your controller Account you have an Action:
public ActionResult Manage(string name) // I presume name
{
....
}
Then your line should be:
Hello, #Html.ActionLink(User.Identity.Name, "Manage", "Account", new { name=User.Identity.Name })!
The anonymous object which is routeValues
It's n object that contains the parameters for a route. The parameters are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.(Definition taken from MSDN) And it should be well formatted.
I hope it will solve the problem otherwise you have to check if the User.Identity is different of null.
I have noticed also somthing else in this line:
var user = db.Users.FirstOrDefault(u => u.EmailAddress == EmailAddress);
Where comes from the EmailAddress after ==?
You should provide a parameter to you Login method to replace your second EmailAddress.
public bool Login(string emailAddress)
{
var user = db.Users.FirstOrDefault(u => u.EmailAddress == emailAddress);
if (user == null)
{
throw new ValidationException("User not found.");
}
else
{
// validates whether or not the password on the user record
// that was retrieved by the query matches the password entered at login
return Hashing.ValidatePassword(Password, user.Password);
}

Resources