Issue with Request.IsAuthenticated after Login page mvc asp.net - asp.net-mvc

I am having an issue with checking the authentication when a user logs in to my site. So I have a login page (Login.cshtml), that of course a user would login from. From there the user would be sent to an index page. My issue is that when i hit this
#if (Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
}
else
{
<strong>Something went wrong</strong>
}
it fails into the else statement and writes something went wrong. Any advice on how to combat this error would be greatly appreciated. Thank you in advance.
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
#if (Request.IsAuthenticated)
{
<strong>#Html.Encode(User.Identity.Name)</strong>
}
else
{
<strong>Something went wrong</strong>
}
My UserContoller(has all the methods for the login):
public ActionResult Index()
{
var user = db.User.Include(u => u.UserName);
var loggedInUser = User.Identity.Name;
return View();
}
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Models.User user)
{
if (ModelState.IsValid)
{
if (isValid(user.UserName, user.Password))
{
FormsAuthentication.SetAuthCookie(user.UserName, false);
return RedirectToAction("Index", "User");
}
else
{
ModelState.AddModelError("", "User Name or Password is incorrect");
}
}
return View(user);
}
private bool isValid(string UserName, string Password)
{
bool isValid = false;
//var user = db.User.SingleOrDefault(u => u.UserName == UserName);
var user = db.User.Where(u => u.UserName == UserName).FirstOrDefault();
var pass = db.User.Where(u => u.Password == Password).FirstOrDefault();
if (user != null && pass != null)
{
isValid = true;
}
return isValid;
}

Related

Can't get action result to run if statement and go to logged in section

For some reason, The users in db.users.Where()is not working like the rest of the users in the code. Need some assistance to make it get to the logged in stage.
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using(DataContext db = new DataContext())
{
var obj = db.users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("LoggedIn");
}
}
}
return View(users);
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}

Asp Core, check if user is in Role in Identity 1.1?

I am using asp.net core 1.1 and identity 1.1. There are 2 roles in my application contains "Admin" and "User". I want "Admin" users navigate to "/AdminProfile/Index" after login and "User" users navigate to "/UserProfile/Index" after login.
My Login Code :
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Error");
return View(model);
}
}
return View(model);
}
And in RedirectToLocal Action :
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
if (User.IsInRole("Admin"))
{
return Redirect("/AdminProfile/Index");
}
else
{
return Redirect("/UserProfile/Index");
}
}
}
I use User.IsInRole("Admin") to verify user role but it always returns false. How can i check user role in identity 1.1?
I can solved it after many research. Try it :
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
var user = await _userManager.FindByNameAsync(model.UserName);
string existingRole = _userManager.GetRolesAsync(user).Result.Single();
return RedirectToLocal(returnUrl,existingRole);
}
else
{
ModelState.AddModelError(string.Empty, "Error");
return View(model);
}
}
return View(model);
}
private IActionResult RedirectToLocal(string returnUrl,string roleName)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
if (roleName == "Admin")
{
return Redirect("/Admin/User");
}
else
{
return Redirect("/User/UserProfile");
}
}
}

Authorize as Roles = "Admin" during login

First of all i am new to MVC user authentication system. Code bellow is working fine for authenticate normal users but i wanted to log all user as per under MVC role based system. So admin user can only see admin controller and normal user cant see admin controller. I already made it on my admin controller i have added "[Authorize(Roles = "Admin")]" and i am also redirecting correctly to specific controller during login filter inside login controller. Now my issue is: How can i tell MVC "[Authorize(Roles = "Admin")]" is only accessed who has admin role? I mean how can i assign a user as admin from my login controller bellow? Ask any question if may have
Administrator Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Blexz.Controllers
{
[Authorize(Roles = "Admin")]
public class AdministratorController : Controller
{
// GET: Administrator
public ActionResult Index()
{
return View();
}
}
}
Login Controller:
//Login post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogin login, string ReturnUrl="")
{
string Message = "";
using (BlexzWebDbEntities db = new BlexzWebDbEntities())
{
var v = db.Users.Where(x => x.Email == login.Email && x.IsEmailVerified == true).FirstOrDefault();
int RoleId = db.Users.Where(x => x.Email == login.Email).Select(x => x.RoleId).FirstOrDefault();
string RoleTypeName = db.Roles.Where(x => x.RoleId == RoleId).Select(x => x.RoleType).FirstOrDefault();
if (v != null)
{
if (string.Compare(Crypto.Hash(login.Password), v.PasswordHash) == 0)
{
int timeOut = login.RememberMe ? 43800 : 100; // 43800 == 1 month
var ticket = new FormsAuthenticationTicket(login.Email, login.RememberMe, timeOut);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeOut);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else if (RoleTypeName == "Admin")
{
return RedirectToAction("Index", "Administrator");
}
else
{
return RedirectToAction("User", "Home");
}
}
else
{
Message = "Invalid Credential Provided";
}
}
else
{
Message = "Invalid Credential Provided";
}
}
ViewBag.Message = Message;
return View();
}
Remove FirstOrDefault from RoleTypeName selection and change it as
string[] RoleTypeName = db.Roles.Where(x => x.RoleId == RoleId).Select(x => x.RoleType);
and change the checking as
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else if (RoleTypeName.Contains("Admin"))
{
return RedirectToAction("Index", "Administrator");
}
else
{
return RedirectToAction("User", "Home");
}
Change your ticket as shown below
var ticket = new FormsAuthenticationTicket(
version: 1,
name: UserName,
issueDate: DateTime.Now,
expiration: DateTime.Now.AddSeconds(httpContext.Session.Timeout),
isPersistent: false,
userData: String.Join(",", RoleTypeName));
and After that in global.asax you would do something like this:
public override void Init()
{
base.AuthenticateRequest += OnAuthenticateRequest;
}
private void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
var roles = decodedTicket.UserData.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
HttpContext.Current.User = principal;
}
}

Print Function using Rotativa

i used Rotativa to print one of my page from html to pdf and when i hit the button to print,it will open print preview,but the preview does not contains that page i just print , it contains and show me log in page in preview instead as you can see,so idont know exactly whats happend.Can someone please point me in the right direction?
The page i tried to print look like this:
But when i hit the button to print,in preview give me log in page:
AccountController:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session["CustomerID"] == null &! Request.RawUrl.ToLower().Contains("login"))
{
Response.Redirect("/Account/Login");
}
base.OnActionExecuting(filterContext);
}
<br>
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Customers cust)
{
using (DataContext db = new DataContext())
{
var user = db.Customers.Where(u => u.CustomerID == cust.CustomerID).FirstOrDefault();
if (user != null)
{
Session["CustomerID"] = user.CustomerID.ToString();
FormsAuthentication.SetAuthCookie(cust.CustomerID, false);
Session.Timeout = 30;
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "CustomerID is not Valid");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["CustomerID"] != null)
{
string customerId = Session["CustomerID"].ToString();
List<Orders> customerOrders;
using (DataContext data = new DataContext())
{
customerOrders = data.Orders.Where(x => x.CustomerID == customerId).ToList();
}
return View(customerOrders);
}
else
{
return RedirectToAction("Login");
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Remove("Login");
return RedirectToAction("Login", "Account");
}
public ActionResult PrintOrders(int id)
{
var report = new ActionAsPdf("ShowOrdersDetails", new { id = id });
return report;
}

Simplemembership Login and RemeberMe ASP.Net MVC4

I am using ASP.net MVC4 with SimpleMemberShip.
I simply want to store the username if the remember me checkbox is ticked and reload it from the cookie.
Login works fine, RememberMe is set to true. But Request.Cookies[FormsAuthentication.FormsCookieName] is always null. I am confused on how this is supposed to work.
Login Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Index(LoginModel model, string returnUrl)
{
bool RememberMe = model.RememberMe == "on" ? true : false;
if (WebSecurity.Login(model.UserName, model.Password, persistCookie: RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
Login Page Controller:
[AllowAnonymous]
public ActionResult Index(string returnUrl)
{
// load user name
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
ViewBag.Username = Server.HtmlEncode(ticket.Name);
ViewBag.RememberMeSet = true;
}
else
{
ViewBag.RememberMeSet = false;
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
I wanted to get the username saved by clicking the "Remember me" checkbox. I now understand the cookie is null unless logged in so it was of no use on a login page. For reference I have added my solution below.
Handle Login Request Controller:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Index(LoginModel model, string returnUrl)
{
// handle remembering username on login page
bool RememberMe = model.RememberMe == "on" ? true : false;
HttpCookie existingCookie = Request.Cookies["xxx_username"];
if (RememberMe)
{
// check if cookie exists and if yes update
if (existingCookie != null)
{
// force to expire it
existingCookie.Expires = DateTime.Today.AddMonths(12);
}
else
{
// create a cookie
HttpCookie newCookie = new HttpCookie("xxx_username", model.UserName);
newCookie.Expires = DateTime.Today.AddMonths(12);
Response.Cookies.Add(newCookie);
}
}
else
{
// remove cookie
if (existingCookie != null)
{
Response.Cookies["xxx_username"].Expires = DateTime.Now.AddDays(-1);
}
}
if ((!string.IsNullOrEmpty(model.UserName)) && (!string.IsNullOrEmpty(model.Password)))
{
if (WebSecurity.Login(model.UserName, model.Password, RememberMe))
{
return RedirectToLocal(returnUrl);
}
}
// If we got this far, something failed, redisplay form
TempData["ErrorMsg"] = "Login failed";
return View(model);
}
Display Login Page Controller:
[AllowAnonymous]
public ActionResult Index(string returnUrl)
{
// load user name
HttpCookie existingCookie = Request.Cookies["xxx_username"];
if (existingCookie != null)
{
ViewBag.Username = existingCookie.Value;
ViewBag.RememberMeSet = true;
}
else
{
ViewBag.RememberMeSet = false;
}
ViewBag.ReturnUrl = returnUrl;
return View();
}

Resources