SimpleMembership Get Custom Column Values with Login - asp.net-mvc-4

I customized UserProfile Table and added new column called IsActive. It works fine with registration.
And now i want to get value of that custom column IsActive before login.
WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe)
Need these scenario
Check if the username and password is valid
If the login is valid then check if the user is active.
If the user is not active it should not login.
Any ideas?

This is just off the top of my head and untested, so it may not be 100% correct, but it should put you in the right direction.
public ActionResult Login(LoginModel model)
{
using(var db = new MyDbContext())
{
try
{
var user = db.UserProfile.FirstOrDefault(x => x.UserName == model.UserName);
if(user != null)
{
if(user.IsActive == true)
{
if(ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
try
{
return View("SomeView");
}
catch(Exception e)
{
// handle exception
}
}
}
else
{
return View("SomeView");
}
}
}
catch(Exception e)
{
// handle exception
}
}
return View("SomeView");
}

Related

ASP.Net Core - Authorize Method doesn't work, it logs out the user

I have been trying to use the authorization method to limit access to specific actions and pages to users that are not logged in. In this case, I am trying to prevent users who are not logged in from purchasing books on my website. Here is how I used the authorize method.
// GET: Books/Purchase/5
[Authorize]
public async Task<IActionResult> Purchase(Guid id)
{
if (id == null)
{
return NotFound();
}
var book = await _context.Book.FindAsync(id);
if (book == null)
{
return NotFound();
}
OrderViewModel model = new OrderViewModel();
model.BookOrder = book;
model.Quantity = 1;
return View(model);
}
When I try to purchase a book the browser takes me back to the login page even though I am already logged in as an admin. What could be the reason for this? Here is my login action:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var result = await signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
if (result.Succeeded)
{
if (!string.IsNullOrEmpty(returnUrl))
{
return LocalRedirect(returnUrl);
}
return RedirectToAction("index", "home");
}
}
ModelState.AddModelError("", "Invalid Login Attempt");
return View(model);
}
Any help/guidance with this?
One reason is that the order of app.UseAuthentication(); and app.UseAuthorization(); is reversed.
You need to make sure app.UseAuthorization(); is after app.UseAuthentication();.
More details you can refer to Asp.Net Core identity.

Redirect To Action Not Working after login ASP.NET Core Identity (.Net 5)

Even after a successful sign-in it does not redirect to action but stays on the login page.
I have put breakpoints but have not been able to know what exactly is wrong with my code.
Even if the condition is true the code is not executed.
Here is my code:
[HttpPost]
public async Task<ActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = await _context.Users.SingleOrDefaultAsync(u => u.UserName == model.UserName);
if (user != null)
{
var result = await _signInManager.PasswordSignInAsync(user, model.Password, true, false);
if (result.Succeeded)
{
var role = await _userManager.GetRolesAsync(user);
if (role.Contains("Client"))
{
return RedirectToAction("Index", "MyDashboard");
}
if (role.Contains("Admin"))
{
return RedirectToAction("Index", "Admin");
}
}
}
else
{
ModelState.AddModelError("", "Invalid login attempt");
return View(model);
}
}
return View();
}
I got the solution myself. Actually, I was missing Authentication middleware in the startup class. After adding app.UseAuthentication() ,it works fine. Thanks.

MVC5 Authentication cannot save UseCookieAuthentication

I have a problem with MVC 5 Authentication
After success login, i think i cannot save UseCookieAuthentication.
My Startup code:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/MyAccount/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}
My login controler:
public ActionResult Login(Login l, string ReturnUrl="")
{
using (CBDB2012Entities dc = new CBDB2012Entities())
{
var user = dc.Users.Where(a => a.UserName.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.UserName, l.RememberMe);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("MyProfile", "MyAccount");
}
}
}
ModelState.Remove("Password");
return View();
}
after login, it RedirectToAction("MyProfile", "MyAccount");
But in MyProfile view, i cannot see anything about user and i cann't access to contac page with [Authorize]:
-Contact controler
[Authorize]
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
I has test via session in login control, and it work fine:
var user = dc.Users.Where(a => a.UserName.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.UserName, l.RememberMe);
Session["loginname"] = user.Employee.FirstName;
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("MyProfile", "MyAccount");
}
}
i can get Session["loginname"] in view from database.

User roles are zero after login in MVC6?

I am using the default site template that comes in visual studio 2015. I have added some roles and assigned roles to the user. When a used signs in, the roles are zero. What do I need to do to get the roles working?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
if (ModelState.IsValid)
{
var signInStatus = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
switch (signInStatus)
{
case SignInStatus.Success:
var user = await GetCurrentUserAsync();
return RedirectToLocal(returnUrl);
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Looking at your code, it looks like you're missing any check for a role.
I was having this similar problem and after digging into the code I noticed that GetCurrentUserAsync() was not returning a valid user object and was intact returning a null object. Context.User.GetUserId() is the problem and isn't returning a user id to pass on to the UserManager.
Until this is resolved I'm using the following:
if (result.Succeeded)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (await UserManager.IsInRoleAsync(user, Roles.Admin))
{
return RedirectToAction("Index", "Admin");
}
return RedirectToLocal(returnUrl);
}
While this isn't ideal it does work
This works for me...does not redirect correct for Invalid username or password 4 me yet...will check...
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
this is for MVC 6, (VS 2015 RC)...u can find it all here : https://github.com/aspnet/Identity/tree/dev/samples/IdentitySample.Mvc

MVC 4 Email.Send Error

I am using Postal to send a confirmation email to a new registered user. But it gets caught in when it hits email.send();. Here is my controller code:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
string confirmationToken =
WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
new { model.Email}, true);
dynamic email = new Email("RegEmail");
email.To = model.Email;
email.UserName = model.UserName;
email.ConfirmationToken = confirmationToken;
email.HostLocation = Request.Url.Host + ':' + Request.Url.Port;
email.Send();
return RedirectToAction("RegisterStepTwo", "Account");
//return RedirectToAction("Index", "Festival");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Does anyone know the problem?