I am not able to get the User.Identity.Name after redirected from controller in Mvc - asp.net-mvc

In the 1st example:-
i am assigning User.Identity.Name value to the variable id. i am able to get the value after that i am Redirecting to some other view here i am using Redirect(ReturnUrl) now i am able to get the User.Identity.Name value in the other controller(Redirected view) also
But in the 2nd example :-
i am assigning User.Identity.Name value to the variable id i am able to get the value after that i am Redirecting to some other view here i am using return Redirect(ReturnUrl);when i am using return Redirect(ReturnUrl);am not able to get the User.Identity.Name value in the Redirected url
Example 1:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
Response.Redirect(ReturnUrl);
return View();
}
Example 2:-
public ActionResult SignIn(string ReturnUrl)
{
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var id=HttpContext.Current.User.Identity.Name;
return Redirect(ReturnUrl);
}
My Controller:- In this function if i am return Redirect(ReturnUrl); i am not able to get the User.Identity.Name value in CompanyRequired filter if i am using Response.Redirect(ReturnUrl); return View(); then able to get the User.Identity.Name value in CompanyRequired filter but i have to use return Redirect(ReturnUrl);
[HttpPost]
public async Task<ActionResult> SignInCallback()
{
var token = Request.Form["id_token"];
var state = Request.Form["state"];
var claims = await ValidateIdentityTokenAsync(token, state);
string ReturnUrl = state.Substring(state.IndexOf('?') + 1);
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
if (ReturnUrl == "/" || string.IsNullOrEmpty(ReturnUrl))
{
ReturnUrl = "/Dashboard";
}
var Id = User.Identity.Name;
return Redirect(ReturnUrl);
}
View:- Here i control will go to the CompanyRequired filter there i need a User.Identity.Name value in that i am getting value null
[Authorize,CompanyRequired]
public class DashBoardController : BaseController
{
public ActionResult Index()
{
return View();
}
}
CompanyRequired Filter:-
public class CompanyRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var coCookie = filterContext.HttpContext.Request.Cookies["CoId"];
if (coCookie == null)
{
var Id= HttpContext.Current.User.Identity.Name.Int(); **//here i need to get the value but i am getting null value**
IdNmList cos = new EmployeeDAL().GetCompany(Id);
if (cos.Count == 0)
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller" , "Company"},
{ "action" , "Add"}
});
}
else if (cos.Count == 1)
{
filterContext.HttpContext.Response.Cookies.Add(new HttpCookie("CoId", cos[0].Id.ToString()));
}
else
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "controller", "Company" },
{ "action", "Select" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
base.OnActionExecuting(filterContext);
}
}

Related

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;
}

passing data(Id) with redircetToAction to url using ViewModel

hello I'm trying to pass the new posted value to a different view with the new value id at the url using RedirectToAction but I'm getting the wrong Url .
Just like here in SO ,that you get redirect to your Q. after submit.
the Url I'm suppose to get is http://localhost:1914/en/evntes/index/60
MyCode(Controler= VoosUp)
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public ActionResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Prametrest
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
// return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id)); //Compiler Error
return RedirectToAction("index", "Events", new { id = lectureGig.Id });//Ok Id 60
}
Events/Index
public ActionResult Index(int id)//OK id=60
{
var lecturegig = _context.LectureGigs.Include(g => g.Artist)
.Include(g => g.Genre)
.SingleOrDefault(g => g.Id == id);
if (lecturegig == null)
return HttpNotFound();
var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };
return View("index", viewmodel);
}
Url i'm getting :http://localhost:1914/en/VoosUp/Create
and the view is correct

Making Sessions in MVC 6 Controller(with views, using Entity Framework)

I'm attempting to create a session in my UserAccountsController
using System.Linq;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.Data.Entity;
using POPPELWebsite.Models;
namespace POPPELWebsite.Controllers
{
public class UserAccountController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserAccount account)
{
if (ModelState.IsValid)
{
using (OurDbContext db = new OurDbContext())
{
db.userAccount.Add(account);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = account.FirstName + " " + account.LastName + " successfully registered.";
}
return View();
}
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (OurDbContext db = new OurDbContext())
{
var usr = db.userAccount.Single(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
Session["UserID"] = usr.UserID.ToString;
}
}
}
}
}
I get an error saying
the name Session does not exist in the current context.
I need to do this part to complete a registration and login tutorial for mvc
The Session property does not exist in the Controller class in MVC 6, instead use HttpContext.Session to access the session property.
Ex:
// get values
string strValue = HttpContext.Session.GetString("StringKey");
int intValue = HttpContext.Session.GetInt32("IntKey");
byte[] byteArrayValue = HttpContext.Session.Get("ByteArrayKey");
// set values
HttpContext.Session.Set("ByteArrayKey", byteArrayValue);
HttpContext.Session.SetInt32("IntKey", intValue);
HttpContext.Session.SetString("StringKey", strValue);
Try this.
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)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
context.Session["UserId"] = obj.UserId.ToString();
context.Session["Username"] = obj.Username.ToString();
return RedirectToAction("Dashboard");
}
}
}
return View(users);
}

Redirect to browsed url after login(authentication)

I have developed a module which authorizes the roles from the database dynamically. Now, what i want is,when a user comes and browses different actionmethod without logging in, I am able to redirect the user to the login page. As soon as the user logs in, he should be redirected to the actionmethod/view which he was trying to access without login. The following is the code which i am using to extract the URL browsed without logging in. I also have a key defined in my web.config as serverURL which gives me initial url like localhost. How to i make the below returnurl remembered and redirect the user to the desired actionmethod/view after logging in.
returnUrl = HttpContext.Current.Request.RawUrl;
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string Feature { get; set; }
public string returnUrl { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//var isAuthorized = base.AuthorizeCore(httpContext);
//if (!isAuthorized)
//{
// return false;
//}
if (httpContext != null && httpContext.Session != null && httpContext.Session["Role"] != null)
{
string userRoles = UserBL.ValidateUsersRoleFeature(httpContext.Session["Role"].ToString(), Feature);
if (!string.IsNullOrEmpty(userRoles))
{
if (userRoles.IndexOf(httpContext.Session["Role"].ToString()) >= 0)
{
return true;
}
}
return false;
}
else
return false;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
if (session.IsNewSession || session["Email"] == null)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// For AJAX requests, return result as a simple string,
// and inform calling JavaScript code that a user should be redirected.
JsonResult result = new JsonResult();
result.ContentType = "text/html";
result.Data = "SessionTimeout";
filterContext.Result = result;
//$.ajax({
// type: "POST",
// url: "controller/action",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// data: JSON.stringify(data),
// async: true,
// complete: function (xhr, status) {
// if (xhr.responseJSON == CONST_SESSIONTIMEOUT) {
// RedirectToLogin(true);
// return false;
// }
// if (status == 'error' || !xhr.responseText) {
// alert(xhr.statusText);
// }
// }
// });
//}
}
else
{
// For round-trip requests,
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "Controller", "User" }, { "Action", "Login" } });
returnUrl = HttpContext.Current.Request.RawUrl;
}
}
else
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Base",
action = "PageNotAccessible"
})
);
}
}
In attribute return the url on which user was in routes:
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "Controller", "User" },
{ "Action", "Login" },
{"returnUrl",HttpContext.Current.Request.RawUrl}
});
and in your action:
[AllowAnonymous]
public virtual ActionResult Login()
{
ViewBag.returnUrl = Request.QueryString["returnUrl"];
return View();
}
In View:
#using(Html.BeginForm("Login","User",new{returnUrl = ViewBag.returnUrl},FormMethod.Post))
{
<input type="submit" value="Login" />
}
and in Post Action:
[AllowAnonymous]
[HttpPost]
public virtual ActionResult Login(User model, string returnUrl)
{
if(ModelState.IsValid)
{
// check if login successful redirect to url from where user came
if(LoginSucessful)
return Redirect(returnUrl); // will be redirected to url from where user came to login
return View();
}
in your html page, create a hidden tag:
<div id="HiddenURL" class="hidden"></div>
the moment the user access a certain page, use Javascript to bind the url the user came from in a hidden value in you web page:
$(document).ready(function ()
{
$('#HiddenURL').text(window.location.href.toLowerCase());
...
}
In your asp.net page assign to action, the url taken from div text:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Base",
action = HiddenURL.Value
})
);
}

Resources