issue on redirecting on log in page when already log in in Mvc3 - asp.net-mvc-3

im having a hard time trying to solve this issue. when i input a username and a password ive always redirect again in log in page. why this happen???
here's my code in login
account controller:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
if (Roles.IsUserInRole("Employer"))
{
return RedirectToAction("CustomerIndex", "Customer");
}
else if (Roles.IsUserInRole("Worker"))
{
return RedirectToAction("WorkerIndex", "Worker");
}
else if (Roles.IsUserInRole("Administrator"))
{
return RedirectToAction("ClientIndex", "Client");
}
else
{
return View(model);
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
thanks.for those who willing to help :)

Looking at your code there are 3 possible cases when this can happen:
Model validation failed -> for example the user didn't provide a username
The user provided incorrect credentials and the ValidateUser method returned false
Credential validation succeeded but the user is not in any of the roles Employer, Worker or Administrator.
Put a breakpoint in your code to see which is your case and act accordingly.

Related

redirecting authorized users to certain pages

I used the identity to assign roles to users.now I want to redirect users according to their role to certain pages.for example user with role"user" after login redirects to a page says" hello user".different from that of admin and so on.I have created the pages and validate authorization each .but where should I redirect after login?
You can simply change the login post action to check the user and redirect to the correct view.
Create separate view for normal users.
NormalUser.cshtml
#{
ViewBag.Title = "Normal User";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Hello User!</h2>
Inside the controller
[Authorize(Roles = "user")]
public ActionResult NormalUser()
{
ViewBag.Message = "Hello normal user.";
return View();
}
Then Login post action
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var user = await UserManager.FindByEmailAsync(model.Email);
var userRole = await UserManager.GetRolesAsync(user.Id);
if (userRole.Any(role => role == "user"))
{
RedirectToAction("NormalUser", "Home");
}
else
{
RedirectToAction("Index", "Home");
}
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
Check this github Project to get the code.

Request.IsAuthenticated Return False all the time

I am having an issue with my Request.IsAuthenticated always return false. I am setting the AuthCookie
CurrentRequest currentRequest = null;
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
} else if (login.ValidateUser(acct.UserName, acct.Password))
{
FormsAuthentication.SetAuthCookie(acct.UserName, true); //Edit on 11/12 #11:08
currentRequest = new CurrentRequest();
SessionWrapper.currentRequest = currentRequest;
return RedirectToAction("About", "Home");
}
//This is a partial login page that is supposed to display login or Logoff.
#using KMSS.Helper;
// this is always false
#if (Request.IsAuthenticated) //Same issue with User.Identity.IsAuthenticated
{
if (SessionWrapper.currentRequest != null)
{
<text> Welcome <strong> #SessionWrapper.currentRequest.Username </strong>
[#Html.ActionLink("Sign Off", "Logoff", "Account")]
</text>
} else {
#: [ #Html.ActionLink("Sign In", "Login", "Account") ]
}
} else
{
#:[ #Html.ActionLink("Sign In", "Login", "Account") ]
}
After reading online, I created a class with a bool value and tries to use that class instead. However, I am getting the object is not set to instance of a new variable exception.
Here is how I had it set up:
//Partial Login page
#model KMSS.Helper.ViewModelAuthenticate;
// this is always false
#if (Model.IsAuthenticated)
//The model is null even though I create create a reference in the Login Method i.e.
(ViewModelAuthenticate auth = new ViewModelAuthenticate();
{
if (SessionWrapper.currentRequest != null)
{
<text> Welcome <strong> #SessionWrapper.currentRequest.Username </strong>
[#Html.ActionLink("Sign Off", "Logoff", "Account")]
</text>
} else {
#: [ #Html.ActionLink("Sign In", "Login", "Account") ]
}
} else
{
#:[ #Html.ActionLink("Sign In", "Login", "Account") ]
}
//Here is the class
public class ViewModelAuthenticate
{
public bool IsAuthenticate { get; set; }
}
//Here is where I am initializing the class in the controller
public ActionResult Login()
{
ViewModelAuthenticate auth = new ViewModelAuthenticate();
auth.IsAuthenticate = false;
return View();
}
//I tried this inside and outside of Login, and it is called before the partial login view. However, I am still getting the object is not set to instance of a new variable exception.
What am I doing wrong here? Your help will be appreciated.
//Showing the authentication section of the config file.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" slidingExpiration="true" />
</authentication>
I replaced my authentication section with this sample that a sample that I found here. It is working now.
Looking at your code, I feel that there is more going on here than you are showing us. Specifically, the variables CurrentRequest and SessionWrapper, setting them to null on the beginning of the Action method call, etc. I would suggest trying a basic, bare bones example in your project and then begin to add items back in as needed. No AJAX, only full page post back to the server from your login form. Such an example would look like:
Login View Model
public class LoginViewModel{
[Required]
public string UserName {get;set;}
[Required]
public string Password {get;set;}
}
Login POST Action method
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl){
if(!ModelState.IsValid){
return View();
}
if(!provider.ValidateUser(model.UserName, model.Password){
ModelState.AddModelError("", "The username/password combination does not match");
return View();
}
FormAuthentication.SetAuthCookie(model.UserName, true);
if(!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl){
return Redirect(returnUrl);
}
return RedirectToAction("About", "Home");
}
About View
#if(Request.IsAuthenticated){
<b>It WORKS!!</b>
}else{
<b>Nope, still not working</b>
}
I was testing and I set my time back a few days. For someone reason it caused this issue after putting the date back it was fine. I assume windows forms had the old date (which was todays date) cached so I assume it was expired. Just a thought about the matter.

Web-Api authentication problems

This is my first ASP.NET project and I want to make a easy login.
I tried this: Link
but I can't understand basic things:
public class AccountController : ApiController
{
public bool Post(LogOnModel model)
{
if (model.Username == "john" && model.Password == "secret")
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return true;
}
return false;
}
}
1) How to code a correct call to this controller?
2) Should not somethings like "credentials" or "Username + PW" instead a LogOnModel?

WebSecurity vs FormsAuthentication in ASP.NET MVC4

I guess I am trying to mix two providers in project but I am looking to use websecurity in conjunction to my forms authentication. I need websecurity for OAUTH authentication using Facebook, and google.
The error that I am getting when I try to login using facebook is
To call this method, the Membership.Provider property must be an instance of ExtendedMembershipProvider.
Here are the code samples. How can I use both?
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
and
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Could possibly be related to the same issue as me MVC4 ExtendedMembershipProvider and entityframework
.. I removed the universal providers nuget package and this particular error dissappeared.
Also this "very recent" article by Jon Galloway may help.
If you are using Visual Studio, you might want to save yourself all this effort. The MVC 4 Internet template comes with four external identity providers out of the box. I have tested them and Google Accounts, Microsoft account, Facebook login, and Twitter login all work fine, with zero lines of code!
I think the same is provided with the Web Form template too.
More info at http://blogs.msdn.com/b/webdev/archive/2012/08/15/oauth-openid-support-for-webforms-mvc-and-webpages.aspx.
You can use an implementation of ExtendedMembershipProvider. For ex: the built-in SimpleMembershipProvider.
Every ExtendedMembershipProvider IS A MembershipProvider .
Read more at Jon Galloway's Blog.

Add User Roles on Registration (Forms Authentication) MVC3

I am developing an MVC 3 project and want to add a user to a role when they are registered, using Forms Authentication. So I'd like to create some check boxes, or a drop down list showing the roles, which are selected and the user is assigned to the role as they are registered.
I have this code so far, which works:
public ActionResult Register()
{
ViewData["roleName"] = new SelectList(Roles.GetAllRoles(), "roleName");
return View();
}
And in the view I have:
<label for="roleName">Select Role:</label>
#Html.DropDownList("roleName")
#Html.ValidationMessage("roleName")
This is HttpPost section of the controller, and this is the part that I don't know what to code:
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
So, all the roles do show up in the view. All I need to know is what to add to the HttpPost section to get this working.
Thanks a lot, Amy
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model.UserName, "RoleName");
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
Try this. It's should work

Resources