Reputation: 22556
I have overriden the IautheticationFIlter in my asp.net web api project. Here is my class:
public class TokenAuthentication : Attribute, IAuthenticationFilter
{
private readonly string realm;
public bool AllowMultiple { get { return false; } }
public TokenAuthentication(string realm)
{
this.realm = "realm=" + realm;
}
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var request = context.Request;
// Receive token from the client. Here is the example when token is in header:
var token = request.Headers.GetValues("Token").ElementAt(0);
...
}
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result, realm);
return Task.FromResult(0);
}
}
Now I need to exclude my login controller from being authenticated:
Curently when I run my project every request trtiggers this code if i put [Authorize], [AllowAnonymous] or no filters at all.
Here is where I add the filter:
public static void RegisterHttpFilters(System.Web.Http.Filters.HttpFilterCollection filters)
{
filters.Add(new TokenAuthentication(""));
}
Upvotes: 3
Views: 3578
Reputation: 159
I think, you mix up authentication and authorization. Probably you want to exclude your login controller from being authorized.
[Authorize] and [AllowAnonymous] attributes are used in the authorization context and have nothing to do with authentication. That's why your IAuthenticationFilter is called every time.
This article could be useful as well http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api.
Upvotes: 1