I'm building my own membership system and I want nothing to do with the MS Membership provider. I've looked around the internet and here on StackOverflow but all I could found was membership providers built on top of the MS Membership provider.
Anyway, I've got almost everything hooked up now, but I'd like to use a custom Authorize attribute which utilized my membership infrastructure. I checked out this thread here on the site and I'm trying to do something similar, but I'm not sure that's quiet what I need. So far these are the classes I've got:
SessionManager:
public static class SessionManager : ISessionManager
{
public static void RegisterSession(string key, object obj)
{
System.Web.HttpContext.Current.Session[key] = obj;
}
public static void FreeSession(string key)
{
System.Web.HttpContext.Current.Session[key] = null;
}
public static bool CheckSession(string key)
{
if (System.Web.HttpContext.Current.Session[key] != null)
return true;
else
return false;
}
public static object ReturnSessionObject(string key)
{
if (CheckSession(key))
return System.Web.HttpContext.Current.Session[key];
else
return null;
}
}
SharweAuthorizeAttribute: (I am not really sure if that's actually what I should be doing)
public class SharweAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true)
return true;
else
return false;
}
}
Now here's what I need:
Is my SharweAuthorizeAttribute class
correct in the first place?
I need to be able to redirect
unauthenticated users to the login
page
I need to authorize users based on
their roles (using my own role
provider) so I would do something
like:
[SharweAuthorize(Roles="MyRole")]
That's it I guess... Any suggestions are more than welcome :)
UPDATE:
Ok I just read that page again and found the solution to question number two:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == false)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "ActionName" },
{ "controller", "ControllerName" }
});
}
else
base.HandleUnauthorizedRequest(filterContext);
}
Let me know if I got it right please...
Yes, you got it right (IMO it's safer and simpler to implement a custom membership provider, but it's your choice)
Yes, it's correct
You do it right
You inherit the roles property from the AuthorizeAttribute base class and you check in your implementation if the user is in the role.
Edit: a little more on the roles thing
if you have
[SharweAuthorize(Roles="MyRole")]
then you can check the Roles property in the AuthorizeCore method
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true) {
if (SessionManager.CheckUserIsInRole( Roles )) // where Roles == "MyRole"
return true;
}
return false;
}
Related
I've a custom AuthorizeAttribute in my website. It has some logic about the Result created for unathorized requests.
In some cases, I want to trigger its validation manually*. I don't know if its possible. As I haven't found how to do that, I thought that I could extract the logic to get the Result to a diferrent method, and call it when I want. But then I don't know how to execute the ActionResult (outside de controllers).
How can I do to manually execute authorize validation? If not possible, how can I do to execute an ActionResult outside a controller?
*I need to trigger it manually because some request may pass the validation (because the session is created) and then, when accessing my services, found that the session was closed by someone else. I wouldn't like to add a call to the services in OnAuthorization to reduce services calls.
I'm not sure if its the best, but I've found a way to get it working (still listening for better answers).
When I call the services and notice that the work session has expired, all I do is removing the active user in the web session.
My custom authorize attribute also implements IResultFilter and IExceptionFilter.
In both OnResultExecuted and OnException I validate the active user once more. If the session was removed, then apply the same ActionResult that I would apply in OnAuthorization.
Here is the final class:
public class CustomAuthorizeAttribute : AuthorizeAttribute, IResultFilter, IExceptionFilter
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
ActionResult result = Validate(filterContext.HttpContext);
if (result != null)
filterContext.Result = result;
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
ActionResult result = Validate(filterContext.HttpContext);
if (result != null)
filterContext.Result = result;
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
}
public void OnException(ExceptionContext filterContext)
{
ActionResult result = Validate(filterContext.HttpContext);
if (result != null)
{
filterContext.Result = result;
filterContext.ExceptionHandled = true;
}
}
public static ActionResult Validate(HttpContextBase httpContext)
{
if (UserActiveInSession)
return null;
// Different rules to build an ActionResult for this specific case.
}
}
I did not get Diego answer's, But Just simply answering the title, I got it to work like that, You can use it as attribute on controllers actions and also trigger it manually at any place in C# or in Razor views.
namespace SomeNameSpace
{
public class CustomAuthorizeAttributeMVC : AuthorizeAttribute
{
private readonly string[] rolesParams;
public CustomAuthorizeAttributeMVC(params string[] roles)
{
this.rolesParams = roles;
}
public bool IsAuthorized { get {
//Do your authorization logic here and return true if the current user has permission/role for the passed "rolesParams"
string[] allowedRoles = new string[] {"role 1", "role 2", "role 3"};
return allowedRoles.Intersect(rolesParams).Any(); //for the example
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return this.IsAuthorized;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
//...
}
}
public class AuthorizeHelper
{
public static bool HasPermission(params string[] roles)
{
return new CustomAuthorizeAttributeMVC(roles).IsAuthorized;
}
}
}
Usage example:
[CustomAuthorizeAttributeMVC("role 2")]
public ActionResult SomeAction()
{
return Content("Authorized !");
}
public ActionResult SomeOtherAction()
{
if(AuthorizeHelper.HasPermission("role 2"))
{
return Content("Authorized !");
}
return Content("401 Not Authorized !");
}
And as said, it can be used in Razor views by calling it normally
#if(AuthorizeHelper.HasPermission("role 2")) {
//...
}
Thanks
I made a functionality that prevents multiple-login for one username at the same time and I call it in Actions like this:
int userId = (int)WebSecurity.CurrentUserId;
if ((this.Session.SessionID != dba.getSessionId(userId)) || dba.getSessionId(userId) == null)
{
WebSecurity.Logout();
return RedirectToAction("Index", "Home");
}
So the point is that every time user logins I save his sessionID into database field. So if someone with same username logins over someone already logged in with same username it overwrites that database field with this new session. If sessionID in DB is not the same as current session ID of logined user it log him out.
Is there a possibility to put this part of code in 1 place or do I have to put it in every single Action in my application?
I tried in Global.asax:
void Application_BeginRequest(object sender, EventArgs e)
{
if (Session["ID"] != null)
{
int userId = Convert.ToInt32(Session["ID"]);
if ((this.Session.SessionID != db.getSessionId(userId)) || db.getSessionId(userId) == null)
{
WebSecurity.Logout();
}
}
}
But I can't use Session here nor WebSecurity class if I try like this:
void Application_BeginRequest(object sender, EventArgs e)
{
int userId = (int)WebSecurity.CurrentUserId;
if ((this.Session.SessionID != db.getSessionId(userId)) || db.getSessionId(userId) == null)
{
WebSecurity.Logout();
Response.RedirectToRoute("Default");
}
}
because I get null reference exception.
EDIT
I used this:
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
int userId = (int)WebSecurity.CurrentUserId;
using (var db = new UsersContext())
{
string s = db.getSessionId(userId);
if ((filterContext.HttpContext.Session.SessionID != db.getSessionId(userId)) || db.getSessionId(userId) == null)
{
WebSecurity.Logout();
filterContext.Result = new RedirectResult("/Home/Index");
}
}
}
I had to use using statement for context, otherwise db.getSessionId(userId) was returning old sessionId. Method is this:
public string getSessionId(int userId)
{
string s = "";
var get = this.UserProfiles.Single(x => x.UserId == userId);
s = get.SessionId;
return s;
}
Very strange, will have to read about why that happened.
Everything works fine, except one thing. I have one JsonResult action in a controller, which returns Json, but since event(its textbox on enter event) can't trigger POST(I assume it's because it logs out before) redirect doesn't work. It can't even post to that Json action to receive callback and redirect. Any clues on that?
success: function (data) {
if (data.messageSaved) {
//data received - OK!
}
else {
// in case data was not received, something went wrong redirect out
window.location.href = urlhome;
}
}
Before I used ActionFilterAttribute I used code to check different sessions inside of POST and of course it could make callback and therefore redirect if didn't receive the data.. But now since it can't even POST and go into method it just stucks there and doesn't redirect :)
I would derive from AuthorizeAttribute. No need to check this information if you don't need to authorize the request.
public class SingleLoginAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
int userId = (int)WebSecurity.CurrentUserId;
if ((filterContext.HttpContext.Session.SessionID != dba.getSessionId(userId))
|| dba.getSessionId(userId) == null)
{
WebSecurity.Logout();
isAuthorized = false;
filterContext.Result = new RedirectResult("/Home/Index");
}
}
return isAuthorized;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult()
{
Data = FormsAuthentication.LoginUrl,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
}
I'd also mention that this allows you to short circuit other ActionFilters because they run after OnAuthorization.
Forward Order - OnAuthorization : AuthorizationFilter (Scope Controller)
Forward Order - OnActionExecuting : ActionFilter1 (Scope Global)
Forward Order - OnActionExecuting : ActionFilter2 (Scope Controller)
Forward Order - OnActionExecuting : ActionFilter3 (Scope Action)
Then as Rob Lyndon mentioned, you could in the FilterConfig (MVC4)
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SingleLoginAuthorizeAttribute());
}
}
Then when you don't want to require any authorization, you can use the AllowAnonymouseAttribute on your ActionResult methods or Controller Class to allow anonymous access.
Update
I added a way for your ajax calls (Get or Post) to work with timeouts. You can do something like:
success: function (jsonResult)
{
if (jsonResult.indexOf('http') == 0)
{
window.location = jsonResult;
}
// do other stuff with the Ajax Result
}
This isn't exactly the best way, but if you want more information on how to do this better I would ask another question instead of appending more questions on this one.
The ActionFilterAttribute is the way to go.
We created an Action Filter called SeatCheck and decorate each controller like this:
[SeatCheck]
public class NoteController : BaseController
{
We use that to get a count of seats and other functions, but it makes it so much easier to control everywhere without thinking about it.
In the proejct ActionFilters folder we have the SeatCheck.cs file that looks like this:
namespace site.ActionFilters
{
public class SeatCheckAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
You can get the SessionID in the Action Filter like this
filterContext.HttpContext.Session.SessionID
Create a custom action filter, and put that code in the filter, then apply the filter to your controller.
Yes, indeed there is. You can use an attribute derived from ActionFilterAttribute.
I would write a class called SessionSecurityAttribute:
public class SessionSecurityAttribute : ActionFilterAttribute
{
public MyDbConn MyDbConn { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var session = filterContext.RequestContext.HttpContext.Session;
if (session["ID"] != null && WebSecurity.IsAuthenticated)
{
int userId = Convert.ToInt32(session["ID"]);
if ((sessionID != MyDbConn.getSessionId(userId)) || MyDbConn.getSessionId(userId) == null)
{
WebSecurity.Logout();
}
}
}
}
The question remains: how can you add these attributes to your actions whilst giving them access to your database? That's easy: in Global.asax you can call into the bootstrapping RegisterGlobalFilters method:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new SessionSecurityAttribute
{
MyDbConn = DependencyResolver.Current.GetService<MyDbConn>()
});
}
This adds your SessionSecurityAttribute, complete with DB connection, to every action by default, without a line of repeated code.
You might try implementing your own custom ISessionIDManager:
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.isessionidmanager.aspx
In the validate, check to see if it's still valid, otherwise return false.
This has had me stumped for a while. None of the commonly encountered similar situations seem to apply here apparently. I've probably missed something obvious but I can't see it.
In my Mvc Web Application I use the Authorize and AllowAnonymous attributes in such a way that you have to explicitly open up an action as publicly available rather than lock down the secure areas of the site. I much prefer that approach. I cannot get the same behaviour in my WebAPI however.
I have written a custom Authorization Attribute that inherits from System.Web.Http.AuthorizeAttribute with the following:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class MyAuthorizationAttribute : System.Web.Http.AuthorizeAttribute
I have this registered as a filter:
public static void RegisterHttpFilters(HttpFilterCollection filters)
{
filters.Add(new MyAuthorizationAttribute());
}
This all works as expected, actions are no longer available without credentials. The problem is that now the following method will not allow the AllowAnonymous attribute to do it's thing:
[System.Web.Http.AllowAnonymous]
public class HomeController : ApiController
{
[GET("/"), System.Web.Http.HttpGet]
public Link[] Index()
{
return new Link[]
{
new SelfLink(Request.RequestUri.AbsoluteUri, "api-root"),
new Link(LinkRelConstants.AuthorizationEndpoint, "OAuth/Authorize/", "authenticate"),
new Link(LinkRelConstants.AuthorizationTokenEndpoint , "OAuth/Tokens/", "auth-token-endpoint")
};
}
}
The most common scenario seems to be getting the two Authorize / AllowAnonymous attributes mixed up. System.Web.Mvc is for web apps and System.Web.Http is for WebAPI (as I understand it anyway).
Both of the Attributes I'm using are from the same namespace - System.Web.Http. I assumed that this would just inherit the base functionality and allow me to inject the code I need in the OnAuthotize method.
According to the documentation the AllowAnonymous attribute works inside the OnAuthorize method which I call immediately:
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
Any thought's would be really appreciated.
Has anyone encountered this problem before and found the root cause?
In the AuthorizeAttribute there is the following code:
private static bool SkipAuthorization(HttpActionContext actionContext)
{
Contract.Assert(actionContext != null);
return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
|| actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
}
Include this method in your AuthorizeAttribute class then add the following to the top of your OnAuthorization method to skip authorization if any AllowAnonymous attributes are found:
if (SkipAuthorization(actionContext)) return;
ASP.NET MVC 4:
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
or
private static bool SkipAuthorization(AuthorizationContext filterContext)
{
Contract.Assert(filterContext != null);
return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()
|| filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
}
Soruce: http://weblogs.asp.net/jongalloway/asp-net-mvc-authentication-global-authentication-and-allow-anonymous
In my case, none of the above solutions worked.
I am using .Net Core 3.1 with a custom IAuthorizationFilter and I had to do the following:
public void OnAuthorization(AuthorizationFilterContext context)
{
if (context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any()) return;
Using MVC 5
Steps to overcome this issue:-
1. Update your Anonymous attribute of WebAPI project and make it like
[System.Web.Mvc.AllowAnonymous]
Now go to your custom attribute class and write the code
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext filterContext)
{
if (filterContext == null)
{
throw new UnauthorizedAccessException("Access Token Required");
}
base.OnAuthorization(filterContext);
if (filterContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
{
return;
}
if (filterContext.Request.Headers.Authorization != null)
{
var response =
PTPRestClient.GetRequest(filterContext.Request.Headers.Authorization.ToString(),
"api/validate/validate-request");
if (!response.IsSuccessStatusCode)
{
throw new UnauthorizedAccessException();
}
}
else
{
throw new UnauthorizedAccessException("Access Token Required");
}
}
Using C#6.0
Create a static class that extends the ActionExecutingContext.
public static class AuthorizationContextExtensions {
public static bool SkipAuthorization(this ActionExecutingContext filterContext) {
Contract.Assert(filterContext != null);
return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()|| filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
}
}
Now your override filterContext will be able to call the extension method, just make sure they are in the same namespace, or include the proper using statement.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustomAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (filterContext.SkipAuthorization()) return;// CALL EXTENSION METHOD
/*NOW DO YOUR LOGIC FOR NON ANON ACCESS*/
}
}
Here is a solution for ASP.NET Core 2+ and ASP.NET Core 3+.
Add it into IAsyncAuthorizationFilter implementation:
private static bool HasAllowAnonymous(AuthorizationFilterContext context)
{
var filters = context.Filters;
return filters.OfType<IAllowAnonymousFilter>().Any();
}
And check like this:
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
if(HasAllowAnonymous(context))
return;
}
I must be using a different version of the .net framework or web api but hopefully this helps someone:
bool skipAuthorization = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any() || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (skipAuthorization)
{
return;
}
public class MyAuthorizationAuthorize : AuthorizeAttribute, IAuthorizationFilter
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
if (skipAuthorization) return;
}
else filterContext.Result = new HttpUnauthorizedResult();
}
}
Ok following up with this thread, here's what I came up with...
public class SharweAuthorizeAttribute : AuthorizeAttribute
{
private bool isAuthenticated = false;
private bool isAuthorized = false;
public new string[] Roles { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true)
{
isAuthenticated = true;
foreach (string role in Roles)
{
if (RolesService.HasRole((string)role))
isAuthorized = true;
}
}
return (isAuthenticated && isAuthorized);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!isAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "User" },
{ "controller", "Login" }
});
} else if(!isAuthorized) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Home" },
{ "controller", "Error" }
});
}
}
}
How/why I came up with this? Because I believe the AuthorizeAttribute workflow goes as follows:
First, AuthorizeCore is triggered. If it returns true, the user is authorized. If it returns false, HandleUnauthorizedRequest is triggered. Is that right?
I read somewhere that I need to use the new keyword to override a property. Therefore, this is how I overrode the Roles property. But what if the overriding property was of a different type of the initial one (the one in the base class), does that also hide it or creates a totally different property?
So what do you think? Should that actually work? I cannot test it now because I haven't set up the UI (waiting for the designer to get done with the design)... In fact, this is the first time I appreciate the benefits of TDD, I used to think it's utterly stupid and useless, but I was wrong :)
P.S: On this thread, #tvanfosson is setting the CachePolicy of the context (I think), could someone explain that and why I might need to do that please?
Thanks in advance.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private readonly bool _authorize;
private readonly string[] _roles;
public CustomAuthorizeAttribute(string roles)
{
_authorize = true;
_roles = roles.Split(',');
}
public CustomAuthorizeAttribute(string roles, bool isAdminPath)
{
_authorize = true;
_roles = roles.Split(',');
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//if controller have role auth and user is not loged
if(_authorize && !httpContext.User.Identity.IsAuthenticated)
return false;
// if controller have role auth and user is loged
if(_roles != null)
{
//grab user roles from DB
var UserRole = RoleRepository.GetUserRole(new Guid(httpContext.User.Identity.Name));
if (_roles.Contains(UserRole))
return true;
}
return false;
}
}
In Controller
[CustomAuthorize("Administrator,Company,OtherRole")]
public ActionResult Test(){
return View();
}
I'm trying to build custom AuthorizeAttribute, so in my Core project (a class library) I have this code:
using System;
using System.Web;
using System.Web.Mvc;
using IVC.Core.Web;
using System.Linq;
namespace IVC.Core.Attributes
{
public class TimeShareAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(!httpContext.Request.IsAuthenticated)
return false;
var rolesProvider = System.Web.Security.Roles.Providers["TimeShareRoleProvider"];
string[] roles = rolesProvider.GetRolesForUser(httpContext.User.Identity.Name);
if(roles.Contains(Website.Roles.RegisteredClient, StringComparer.OrdinalIgnoreCase))
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/TimeShare/Account/LogOn");
base.HandleUnauthorizedRequest(filterContext);
}
}
}
When I try to build the thing I get this error:
Error 2 'IVC.Core.Attributes.TimeShareAuthorizeAttribute.AuthorizeCore(System.Web.HttpContextBase)': no suitable method found to override ...
Am I missing something here? I've searched all over but every site I can find just tells me to do exactly what I did here. I'm using mvc2 btw.
Edited to add: if I move the class to the mvc project in the same solution there's no compiler error.
Yeah, I fumbled with that one for a while too and figured it out from the Object browser. It certainly is NOT clear from the MSDN docs unless you scroll all the way down to the user comments on the HttpContextBase class. And, of course, lots of examples on the web, but nobody ever shows the full class file! :)
Try adding a reference to System.Web.Abstractions to your project.
UPDATE: Just noticed from the MSDN that under v3.5, it is under System.Web.Abstractions, but under v4, it's under System.Web.
Here is AuthorizationAttribute.cs
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This software is subject to the Microsoft Public License (Ms-PL).
* A copy of the license can be found in the license.htm file included
* in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
namespace System.Web.Mvc {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
Justification = "Unsealed so that subclassed types can set properties in the default constructor or override our behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter {
private string _roles;
private string[] _rolesSplit = new string[0];
private string _users;
private string[] _usersSplit = new string[0];
public string Roles {
get {
return _roles ?? String.Empty;
}
set {
_roles = value;
_rolesSplit = SplitString(value);
}
}
public string Users {
get {
return _users ?? String.Empty;
}
set {
_users = value;
_usersSplit = SplitString(value);
}
}
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}
return true;
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) {
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext)) {
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */);
}
else {
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
}
// This method must be thread-safe since it is called by the caching module.
protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
bool isAuthorized = AuthorizeCore(httpContext);
return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;
}
internal static string[] SplitString(string original) {
if (String.IsNullOrEmpty(original)) {
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}
}
Also, since I've seen this happen before, be careful with letting Visual Studio auto add usings for you. If you're not paying attention you may end up adding System.Web.Http instead of System.Web.Mvc.
When I copied my old codes to my new project, the same problem happened.
It turned out that there are 2 AuthrizeAttributes. One is in System.Web.Mvc, and another in System.Web.Http.
The Mvc one has the AuthrizeCore, while the Http one has not.
You might need to add reference to System.Web.Mvc to access the right one.
I had this error too. It turned out that Visual Studio had added to my ActionFilter by default:
using System.Web.Http;
Even when I added System.Web.Mvc I still got the error. Commenting out System.Web.Http and just using System.Web.Mvc seems to solve the problem for me.
Hoping this might help someone!
Use System.Web.Mvc namespace.
Sample code:
using System.Web.Mvc;
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
var service = new AuthService();
return service.GetCurrentUser() != null;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
Under fw v4.5 it now under System.Web.Mvc apparently.