Custom ASP.NET attribute not getting called - c#

I have a custom Authorization attribute not getting called in my asp.net class and I can't tell what I'm missing.
My Attribute looks like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyAuthorize : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// ...
}
protected bool AuthorizeCore(HttpContextBase httpContext)
{
// Logic here.
return false;
}
}
And I'm calling it from inside a WebService like so:
[WebService(Namespace = "http://something/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class AccessPoint : System.Web.Services.WebService
{
[WebMethod]
[MyAuthorize]
public bool SomeWebMethod(int a)
{
//Do stuff
return false;
}
}
Each time I run it, it will fall right through and never trigger the attribute.
FYI; I used System.Web.Http.AuthorizeAttribute because System.Web.Mvc.AuthorizeAttribute was telling me that AuthorizeAttribute did not exist.

You seem to be making a terrible confusion here between ASP.NET Web API and legacy classic ASMX WebServices. You have written an ASP.NET Web API authorization attribute (designed to be used in an ASP.NET API REST service) and applied it on a legacy ASMX WebService. Those two technologies are completely different and should not be mixed together.
It's like trying to put a Lamborghini engine on a horse driven cart.

Related

Authorize with a specific scheme in ASP.NET MVC 4

Is there a way to require a specific Authorization Scheme when using the [Authorize] Attribute on a Controller in asp.net MVC 4?
I expected something like this (which is totally possible in .net core btw)
[Authorize(AuthenticationSchemes = "Bearer")]
public class MyController : Controller { }
As far as I know, there is nothing out of the box that would allow you to write this.
The standard authorize attribute doesn't support this.
But you could write your own attribute and check the claims of the identity coming in.
I used an backport of ASP.NET Core authorization policies to .NET Full framework: https://github.com/DavidParks8/Owin-Authorization to write such rules.
How to check of you come from which token?
Normally you will see a claim similar to "idp": "oidc"
How to get the claims? ((ClaimsPrinciple)User).Claims ( in Controller code)
As suggested by #Chetan Ranpariya in the comments I ended up implementing a derived attribute (from AuthorizeAttribute). According to the documentation, overriding the AuthroizeCore method is the way to do it.
When overridden, provides an entry point for custom authorization checks.
Here is a working example for future reference
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public string AuthSchemes { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (this.AuthSchemes != null)
{
string scheme = httpContext?.User?.Identity?.AuthenticationType;
if (string.IsNullOrWhiteSpace(scheme))
{
return false;
}
return this.AuthSchemes.Split(',').Contains(scheme);
}
return base.AuthorizeCore(httpContext);
}
}
The attribute can be used like this
[MyAuthorize(AuthSchemes = CookieAuthenticationDefaults.AuthenticationType)]
public class MyController : Controller { }

MVC API2 ActionFilterAttribute not called

I am struggeling with this peace of code:
public class MultiDatabaseAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
I want to execute the OnActionExecuting on certain ActionResults in my API. This is a method in my API:
[MultiDatabase]
public Website Get(int id)
{
return _websites.Get(id);
}
It does not work. Whatever I try, the method attribute is not called. According to the website http://www.strathweb.com/2015/06/action-filters-service-filters-type-filters-asp-net-5-mvc-6/ this should work.
According to this question I had to add the attribute to the Global.asax. Did not help too.
Who can help me?
Thanks
You are inheriting your attribute from the wrong base class. MVC and WebAPI have different objects (at least until ASP.Net Core has since merged them into one). Make sure you have the correct import in your attribute:
using System.Web.Http.Filters;
Or use the full namespace:
public class MultiDatabaseAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
}
}

MVC Web API custom basic authentication

I have a database with users, the users can have different roles.
I want to implement basic authentication for my MVC Web API and I want to be able to tag methods with an Authorize tag and also pass userType as a parameter.
[Authorize(admin)]
public bool Test()
{
}
[Authorize(user)]
public bool Test1()
{
}
I can't figure out how to make this attribute, for example how do I make an attribute that simply makes a method always return false?
[AttributeUsage(AttributeTargets.All)]
public class TestAttribute: System.Attribute
{
//Return false?
}
I'm looking for some advice.
EDIT:
I made the following class:
ilterContext.HttpContext.Response.StatusCode = 401;
filterContext.Result = new EmptyResult();
filterContext.HttpContext.Response.End();
}
}
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
{
then i add [BasicAuthorize] to a method, but it still let me access it without basic autentication.
any idea?
I suggest you read some basics about authorization and authentication and how the Authorize attribute can be applied.
Roles are out of the box. Just use the built-in capabilities of the Authorize attribute: Example:
[Authorize(Roles="admin")]
public bool Test()
{
}
If you need a custom implementation you need to inherit from System.Web.Mvc.AuthorizeAttribute instead of from System.Attribute. Everything else is pretty straight forward from here. Basic example explained here: Basic Authorization Attribute in ASP.NET MVC

Executing code when accessing API controllers

I have the following code:
CookieHeaderValue cookie = Request.Headers.GetCookies("session").FirstOrDefault();
var isAuthenticated = _userService.IsAuthenticated(cookie);
if (!isAuthenticated)
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "");
I'd like this code to execute as soon as any part of my api is called. I havn't found any good solutions or ways to do this so i thought i would ask here instead.
(what I do now is execute the code in every get/post/put/delete which is horrible).
The best place to solve this would be an authorization filter attribute. See Authentication Filters in ASP.NET Web API 2.
The subject is too broad to repeat here in its entirety, but it comes down to creating an attribute:
public class CookieAuthenticationFilterAttribute : Attribute, IAuthenticationFilter
{
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
// your cookie code
}
}
And applying it to the controller or action methods:
[YourCookieAuthentication]
But be sure to read the link.
You can use an ActionFilter or AuthorizationFilter for this purpose. These are attribute classes that you can use on specific controllers/actions or globally. So you don't need to repeat the code for every action.
See this link for details. It shows the general authentication/authorization flow in ASP.NET Web API and how you can customize it.
So i found the best solution for my problem was the following code:
public class CookieFilterAttribute : AuthorizeAttribute
{
[Inject]
public IUserService UserService { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
CookieHeaderValue cookie = actionContext.Request.Headers.GetCookies("session").FirstOrDefault();
var isAuthenticated = UserService.IsAuthenticated(cookie);
return isAuthenticated;
}
}

Custom AuthorizeAttributte with Enum Roles params getting null Values in ajax call

I'm having some problem with my custom AuthorizeAttribute
public class ExplicitAuthorizeAttribute : AuthorizeAttribute
{
private readonly MembershipUserRole[] _acceptedRoles;
public ExplicitAuthorizeAttribute()
{
}
public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
{
_acceptedRoles = acceptedRoles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Validation ...
}
}
I use it like this:
[ExplicitAuthorize[(MembershipUserRole.Admin, MembershipUserRole.SuperAdmin)]
It works perfectly for HttpGet and HttpPost to validate my controllers and methods.
But when I use it in a ApiController and make ajax calls, AuthorizeCore isn't running and I got a security breach. :/
My enum looks like this
[Flags]
public enum MembershipUserRole
{
Admin= 1,
SuperAdmin = 2
}
Does anyone know why my AuthorizeCore isn't validating in this context?
By the way If I use
[Authorized(Roles ="Admin, SuperAdmin")]
It's validates perfectly, but I'd like to have Stronly Typed Roles,that's why I'm using enums.
You have derived from the wrong class: System.Web.Mvc.AuthorizeAttribute whereas for a Web API controller you should derive from System.Web.Http.AuthorizeAttribute.
Don't forget that ASP.NET MVC and ASP.NET Web API are 2 completely different frameworks and even if they share some common principles and names, the corresponding classes are located in 2 completely different namespaces.
So what you have done is decorate an ASP.NET Web API action with an AuthorizeAttribute that it doesn't know anything about.
If you want to make authorization in ASP.NET Web API make sure you have derived from the correct attribute:
public class ExplicitAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
private readonly MembershipUserRole[] _acceptedRoles;
public ExplicitAuthorizeAttribute()
{
}
public ExplicitAuthorizeAttribute(params MembershipUserRole[] acceptedRoles)
{
_acceptedRoles = acceptedRoles;
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
//Validation ...
}
}

Categories