I want to do custom authentication because we have many controllers and it makes sense to create global filter that applies for all controllers and their actions with exception of login page.
In Global.asax.cs I added next global filter:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e) // Code that runs on application startup
{
... // only showing important part
GlobalFilters.Filters.Add(new Filters.AuthenticationUserActionFilter());
...
}
File AuthenticationUserActionFilter.cs:
public class AuthorizeUserActionFilter : System.Web.Mvc.Filters.IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousActionFilter), inherit: true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousActionFilter), inherit: true);
if (skipAuthorization) // anonymous filter attribute in front of controller or controller method
return;
// does this always read value from ASPXAUTH cookie ?
bool userAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
if (!userAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Login" } });
return;
}
if( HttpContext.Current.User as Contracts.IUser == null )
{
// check if IUser is stored in session otherwise retrieve from db
// System.Web.HttpContext.Current.User is reseted on every request.
// Is it ok to set it from Session on every request? Is there any other better approach?
if (HttpContext.Current.Session["User"] != null && HttpContext.Current.Session["User"] as Contracts.IUser != null)
{
HttpContext.Current.User = HttpContext.Current.Session["User"] as Contracts.IUser;
}
else
{
var service = new LoginService();
Contracts.ISer user = service.GetUser(filterContext.HttpContext.User.Identity.Name);
HttpContext.Current.Session["User"] = user;
HttpContext.Current.User = user;
}
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) {}
}
My login code is like this (in AccountController.cs):
[Filters.AllowAnonymousActionFilter]
[HttpPost]
public JsonResult Login(string username, string password, bool rememberMe = false)
{
LoginService service = new LoginService();
Contracts.IUser user = service .Login(username, password);
System.Web.HttpContext.Current.Session["User"] = value;
System.Web.HttpContext.Current.User = value;
// set cookie i.e. ASPX_AUTH, if remember me, make cookie persistent, even if user closed browser
if (System.Web.Security.FormsAuthentication.IsEnabled)
System.Web.Security.FormsAuthentication.SetAuthCookie(username, rememberMe);
return new SuccessResponseMessage().AsJsonNetResult();
}
Contracts.IUser interface:
public interface IUser : IPrincipal
{
Contracts.IUserInfo UserInfo { get; }
Contracts.ICultureInfo UserCulture { get; }
}
My question is this:
System.Web.HttpContext.Current.User is reseted on every request. Is it ok to set HttpContext.Current.User with Session value on every request? Is there any other better approach? What is best practise? Also Microsoft seems to have multiple ways of dealing with this problem (googled a lot of articles on this, also on stackoverflow Custom Authorization in Asp.net WebApi - what a mess?). There is a lot of confusion about this, although they developed a new Authorization in asp.net core.
One possible approach is to serialize the user as part of the UserData portion of the ASPXAUTH cookie. This way you don't need to fetch it from the database on each request and you don't need to use Sessions (because if you use sessions in a web-farm you will have to persist this session somewhere like in a database, so you will be round-tripping to the db anyway):
[Filters.AllowAnonymousActionFilter]
[HttpPost]
public JsonResult Login(string username, string password, bool rememberMe = false)
{
LoginService service = new LoginService();
Contracts.IUser user = service.Login(username, password);
string userData = Serialize(user); // Up to you to write this Serialize method
var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(24), rememberMe, userData);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket));
return new SuccessResponseMessage().AsJsonNetResult();
}
And then in your custom authorization filter you could decrypt the ticket and authenticate the user:
public void OnAuthentication(AuthenticationContext filterContext)
{
... your stuff about the AllowAnonymousActionFilter comes here
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
{
// Unauthorized
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary() { { "controller", "Account" }, { "action", "Login" } });
return;
}
// Get the forms authentication ticket.
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
Contracts.ISer user = Deserialize(authTicket.UserData); // Up to you to write this Deserialize method -> it should be the reverse of what you did in your Login action
filterContext.HttpContext.User = user;
}
Related
Here is my code. I have written login to validate the token, for valid token return user object. but unable to find way to make it available across controllers.
I don't want to use Identity.
public class CustomAuthorize : AuthorizeAttribute
{
private const string AUTH_TOKEN = "AuthToken";
public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
AllowAnonymousAttribute allowAnonymousAttribute = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().FirstOrDefault();
if (allowAnonymousAttribute != null)
{
return Task.FromResult<object>(null);
}
if (actionContext.Request.Headers.Contains(AUTH_TOKEN))
{
var authToken = actionContext.Request.Headers.GetValues(AUTH_TOKEN).First();
var user = Utility.GetUserByToken(authToken);
if (user != null)
{
//
// how to make this `user` object available across the controllers
//
return Task.FromResult<object>(null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new CustomError() { Code = 100, Message = "Invalid Access Token" });
return Task.FromResult<object>(null);
}
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new CustomError() { Code = 100, Message = "Invalid Access Token" });
return Task.FromResult<object>(null);
}
}
}
Please help...
Your Question is a bit unclear - I assume you are referring to this line:
var user = Utility.GetUserByToken(authToken);
If so, then I might have a solution. So the fundamental problem is that you cannot simply save this variable where you currently are in the current controller, you need to understand the context you are working in - Every time a different user makes a request a different user models get created in the current controller. To have access to the user model across my app whenever a user makes a request, I do the following:
First you need to hook into the request receiving process of ASP.NET. This can be done inside the Global.asax.cs file, but I prefer to keep it clean and create a PartialGlobal class and mark the Global.asax.cs as partial.
From
public class MvcApplication : System.Web.HttpApplication
To
public partial class MvcApplication : System.Web.HttpApplication
Then create the PartialGlobal Class:
public partial class MvcApplication
{
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var request = HttpContext.Current.Request;
var authHeader = request.Headers["Authorization"];
//For API users
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
if (authHeaderVal.Scheme.Equals("Basic", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(authHeaderVal.Parameter))
{
AuthenticateUser(authHeaderVal.Parameter);
}
}
}
//For Regular Website Users
else
{
HttpCookie authCookie = request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching userData field then extract
var userModel = UsersBLL.DeserializeObject(authTicket.UserData);
var principal = new UserPrincipal(userModel);
SetPrincipal(principal);
}
}
}
private static bool AuthenticateUser(string credentials)
{
var model = UsersBLL.DecryptToken(credentials);
if (!model.RefUser.HasValue)
{
return false;
}
SetPrincipal(new UserPrincipal(model));
return true;
}
private static void SetPrincipal(UserPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
}
The UserPrincipal Class:
public class UserPrincipal : IPrincipal
{
public IIdentity Identity { get; private set; }
//Just a class with details like name,age etc.
public UserModel Model { get; set; }
public UserPrincipal(UserModel model)
{
this.Model = model;
this.Identity = new GenericIdentity(model.Email);
}
}
Note the line in the PartialGLobal class: var model = UsersBLL.DecryptToken(credentials);. Here I simply use a method I created to de-crypt my token string so it can be deserialized, you probably won't have/need this.
The essential part is this last step of the PartialGlobal class:
private static void SetPrincipal(UserPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
If you have the context know about your user, you can access it anywhere by simply calling:
var principal = (UserPrincipal)HttpContext.Current.User;
One way is to Extend the ApiController which is what your controllers are using as the base class.
Define a CustomController
public class CustomController : ApiController
{
projected User _user;
}
For all the other controller use this as a base class and the _user object should be accessible from all the controllers.
I have extended the Authorize attribute to include roles which comes from a cookie. Debugging gives good result, it returns true or false accordingly. However if I first log in with "Admin" Role and then try to go to a controller that requires a User role, the Authorize returns false but still the controller allows access.
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (httpContext.User != null)
{
if (httpContext.User.Identity.IsAuthenticated)
{
if (httpContext.User.Identity is FormsIdentity)
{
FormsIdentity id = httpContext.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = id.Ticket;
string role = ticket.UserData;
if (RequiredRole.Contains(role)) return true;
}
}
else
return false;
}
return false;
}
Requiredrole is a property of the class.
[CustomAuthorize(RequiredRole = "Admin", LoginPage = "Club")]
public class UsuarioAdminController : Controller
{
above code for a controller that requires admin role.
[CustomAuthorize(RequiredRole = "User", LoginPage = "Club")]
public class HotelController : Controller
{
above code for a controller with User role.
Can someone see why if Authorize returns false it allows access? Thanks
The AuthorizeCore Attribute behave as expected, it returns true or false; however the controller allows access when the AuthorizeCore method returns false.
Yes, there is more code, but I dont think it makes a differnce..here it is.
public class CustomAuthorizeAttribute: AuthorizeAttribute
{
public string RequiredRole;
public string LoginPage;
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (httpContext.User != null)
{
if (httpContext.User.Identity.IsAuthenticated)
{
if (httpContext.User.Identity is FormsIdentity)
{
FormsIdentity id = httpContext.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = id.Ticket;
string role = ticket.UserData;
if (RequiredRole.Contains(role)) return true;
}
}
else
return false;
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
var routeValues = new RouteValueDictionary();
if (LoginPage == "Club")
{
routeValues["action"] = "Index";
routeValues["controller"] = LoginPage;
routeValues["ReturnUrl"] = filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectToRouteResult(routeValues);
}
else {
routeValues["area"] = "mobile";
routeValues["action"] = "login";
routeValues["controller"] = LoginPage;
routeValues["ReturnUrl"] = filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectToRouteResult(routeValues);
}
}
}
}
I found the answer to this particular situation and I am sharing my findings. When a request was properly unauthorized it was handled by the
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
method. Inside that method I was checking first if the user is not authenticated. For the first request it works properly sending the user to the appropriate log in page, But now if you try to navigate to another page that requires a different role, because you are already authenticated it wont go inside the redirect and will allow access to the control. So by removing the !IsAuthenticated if at the beginning, now all unauthorized request is properly sent to the correct login page...
I have a custom ActionFilterAttribute that makes sure a value in the Session matches a value in the database. If the values don't match, it redirects the user to the Login action on the AccountController.
public class CheckSessionAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
{
// If the action allows Anonymous users, no need to check the session
return;
}
var session = filterContext.RequestContext.HttpContext.Session;
var userName = filterContext.RequestContext.HttpContext.User.Identity.Name;
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(userName).Result;
if (userName == null || user == null || session == null || session["ActiveSessionId"] == null ||
session["ActiveSessionId"].ToString() != user.ActiveSessionId.ToString())
{
session.RemoveAll();
session.Clear();
session.Abandon();
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new
{
action = "Login",
controller = "Account"
}
));
}
base.OnActionExecuting(filterContext);
}
}
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
SignOutAndKillSession();
ViewBag.ReturnUrl = returnUrl;
return View();
}
private void SignOutAndKillSession()
{
AuthenticationManager.SignOut();
Session.RemoveAll();
Session.Clear();
Session.Abandon();
}
}
When I try to login again after being redirected to the Login action, I get the following exception:
The provided anti-forgery token was meant for a different claims-based user than the current user
I set a breakpoint inside the Login action and can see that User.Identity.Name is still set to the user that is being logged out, before AND after the call SignOutAndKillSession(). I believe this is what's causing an incorrect AntiForgeryToken to be generated when the page renders.
Can someone help me find out how to clear the User Principal when logging out a user?
Thanks
For anyone that runs into this issue, I solved it by expiring the cookies created by MVC 5 inside the CheckSessionAttribute. I also changed the attribute from an ActionFilterAttribute to an IAuthorizationFilter Attribute
public class CheckSessionAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
{
// If the action allows Anonymous users, no need to check the session
return;
}
var session = filterContext.RequestContext.HttpContext.Session;
var userName = filterContext.RequestContext.HttpContext.User.Identity.Name;
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(userName).Result;
if (userName == null || user == null || session == null || session["ActiveSessionId"] == null ||
session["ActiveSessionId"].ToString() != user.ActiveSessionId.ToString())
{
session.RemoveAll();
session.Clear();
session.Abandon();
ExpireCookie("ASP.NET_SessionId", filterContext);
ExpireCookie("__RequestVerificationToken", filterContext);
ExpireCookie(".AspNet.ApplicationCookie", filterContext);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new
{
action = "Login",
controller = "Account"
}
));
}
return;
}
private void ExpireCookie(string name, AuthorizationContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.Cookies[name] != null)
{
filterContext.RequestContext.HttpContext.Response.Cookies[name].Value = string.Empty;
filterContext.RequestContext.HttpContext.Response.Cookies[name].Expires = DateTime.Now.AddMonths(-20);
}
}
}
I have the following login method in my MVC project
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (_authenticationRepository.Login(model.UserName, model.Password))
{
var authenticationTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now,
DateTime.Now.AddMinutes(20),
model.RememberMe, "", "/");
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(authenticationTicket));
Response.Cookies.Add(cookie);
UserContext.CreateUserContext();
return RedirectToLocal(returnUrl);
}
}
UserContext.cs
This stores the user/permissions into a session.
public static void CreateUserContext()
{
BuildUserContext(HttpContext.Current.User);
}
private static void BuildUserContext(IPrincipal principalUser)
{
if (!principalUser.Identity.IsAuthenticated) return;
var user = _userAccountsRepository.GetUserByUserName(principalUser.Identity.Name);
if (user == null) return;
var userContext = new UserContext { IsAuthenticated = true };
var siteUser = Mapper.Map(user);
userContext.SiteUser = siteUser;
HttpContext.Current.Session["UserContext"] = userContext;
}
I am aware that IsAuthenticated will only become true after a redirect. So within my login() method, is it possible to ensure that principalUser.Identity.IsAuthenticated will return true?
Or where else will be a good place to create the user context if not it the login method?
What I'm trying to achieve is:
user logs in
if login is successful, query db for his roles/permissions and save them into a session so that I don't have to requery every time I'm checking if the user has access to a certain action.
You could do something like follows:
When user logs in for the first time, get user's role/permission details, serialize it and store it in the session. So as this session is in the memory, every time you want to check if user has permission to an operation deserialize this from memory instead of going to the database.
This is my Global.asax.cs file:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
...
}
protected void Application_Start()
{
this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
}
// This method never called by requests...
protected void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { });
Context.User = principal;
}
}
}
When PostAuthenticateRequest gets execute?
According to the documentation:
Occurs when a security module has
established the identity of the user.
...
The PostAuthenticateRequest event is
raised after the AuthenticateRequest
event has occurred. Functionality that
subscribes to the
PostAuthenticateRequest event can
access any data that is processed by
the PostAuthenticateRequest.
And here's the ASP.NET Page Life Cycle.
But because your question is tagged with ASP.NET MVC I would strongly recommend you performing this into a custom [Authorize] attribute instead of using this event. Example:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { });
httpContext.User = principal;
}
}
return isAuthorized;
}
}
Now decorate your controllers/actions with the [MyAuthorize] attribute:
[MyAuthorize]
public ActionResult Foo()
{
// if you got here the User property will be the custom
// principal you injected in the authorize attribute
...
}
If you place your code on PostAuthenticateRequest you may get hit many times per request as every resource such as images and style sheets referenced on your page will trigger this event as they are treated as separate requests.
If you go with #Darin's answer, the AuthorizeAttribute won't render the action when isAuthorized returns false, but people may need it to be rendered anyway, even if its a public page (unrestricted access) you may want to show a "Display Name" saved on the userData part of the authTicket.
For that, I recommend loading the authCookie on an ActionFilterAttribute (AuthenticationFilter):
public class LoadCustomAuthTicket : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
if (!filterContext.Principal.Identity.IsAuthenticated)
return;
HttpCookie authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var identity = new GenericIdentity(authTicket.Name, "Forms");
var principal = new GenericPrincipal(identity, new string[] { });
// Make sure the Principal's are in sync. see: https://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx
filterContext.Principal = filterContext.HttpContext.User = System.Threading.Thread.CurrentPrincipal = principal;
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//This method is responsible for validating the current principal and permitting the execution of the current action/request.
//Here you should validate if the current principle is valid / permitted to invoke the current action. (However I would place this logic to an authorization filter)
//filterContext.Result = new RedirectToRouteResult("CustomErrorPage",null);
}
}
And on global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LoadCustomAuthTicket());
}
That way you also won't have to populate all your actions with the attribute.