I'm in an ASP.NET 4.6 Web Forms application.
I am trying to use claims to check if a user is authorized to payroll page like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!ContainsClaim(User.Identity.Name, "role", "admin"))
{
//execute function 1
Response.Redirect("Account/Login.aspx");
}
}
public bool ContainsClaim(string userName, string claimType, string claimValue)
{
ApplicationDbContext context = new ApplicationDbContext();
var user = context.Users.Where(s => s.UserName == "rsadmin").FirstOrDefault();
if (user == null)
{
return false;
}
return user.Claims.Where(s => s.ClaimType == claimType && s.ClaimValue == claimValue).Count() > 0;
}
A payroll user clicked on the payroll page before logging in. So she got redirected to login page. How can I automatically direct them back to payroll page after logging in?
There are several options.
You can use a query parameter for returnUrl which you can use to redirect upon login. If you do use a query parameter, make certain that the returnUrl is actually set to a url on your site before redirecting; otherwise your page could be used by hackers to get users to visit a nefarious site.
Another option is to use the session (if available) to store information regarding what the user tried to access and redirect from the session variable.
protected void Page_Load(object sender, EventArgs e)
{
if (!ContainsClaim(User.Identity.Name, "role", "admin"))
{
//execute function 1
Response.Redirect("Account/Login.aspx?ReturnUrl="+HttpUtility.UrlEncode(Request.Url.PathAndQuery));
}
}
To check if the page is on the same server:
var redirUrl = HttpUtility.UrlDecode(Request["ReturnUrl"]);
if(!string.IsNullOrWhiteSpace(redirUrl)){
var mappedPath = Page.MapPath(redirUrl.Trim());
if(File.Exists(mappedPath)){
Response.Redirect(redirUrl.Trim());
}
}