Reputation: 2372
I have two problems with the following method (Web API 2, C#, .Net Framework 4.8):
[AllowAnonymous]
public JSONObject TestMeAno()
{
return new JSONObject() { id = 333 };
}
I have implemented a custom authorization filter "MyCustomAttribute" as this:
public class AuthorizeJWTAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
try
{
base.OnAuthorization(actionContext);
bool isAuthorized = false;
int countAnon= actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>();
System.Net.Http.Headers.AuthenticationHeaderValue authorizationHeader = actionContext.Request.Headers.Authorization;
if (actionContext != null && (authorizationHeader != null) && (authorizationHeader.Scheme.CompareTo("Bearer") == 0) && !(String.IsNullOrEmpty(authorizationHeader.Parameter)))
{
string token = authorizationHeader.Parameter;
CommercialInsurance.Common.Helpers.DecodeJWTToken(token); // Will throw an exception if the token cannot be decode.
// If code arrives to here, than all is good, user is authorized.
isAuthorized = true;
}
if (!isAuthorized)
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
catch (Exception)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
}
I have decorated the controller with [MyCustomAttribute]. When I call the API TestMeAno() it is not passing the authorization. When I check this statement:
int countAnon= actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>();
countAnon is always 0 even though the method is decorated by AllowAnonymous.
The second issue is that even that the use is authorized (the function ends with no error and no 401 response) there is a message that is being returned "Authorization has been denied for this request". I don't know from where this message comes.
EDIT If I change
System.Web.Http.AuthorizeAttribute
to
System.Web.Http.Filters.AuthorizationFilterAttribute
. The second issue will be resolved, but the first not.
Upvotes: 1
Views: 239