I have an MVC 5 site that also contains an API that's using Web API 2. I want to use Identity 2.0 to control access to the web pages - simple. But I want to use Basic Authentication or some other custom authentication on my api controllers, placed inside an Api folder (as is customary).
I have a custom IAuthenticationFilter written which controls access to the API, but if it returns a 401, Identity takes over and converts it to a 302 for redirection to the web site logon page. I want to prevent this conversion, but can't see any way.
In my OWIN Startup class's ConfigureAuth(IAppBuilder) method I have:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, oginPath = new PathString("/Account/LogOn") }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
My BasicAuthenticationFilter has this:
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { context.Result = new AddChallengeOn401Result() { Request = context.Request }; return Task.FromResult(0); } private class AddChallengeOn401Result : IHttpActionResult { public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=MyRealm")); return Task.FromResult(response); } }
The problem is that after ExecuteAsync is done, I'm expecting to have returned a 401, but after that point ASP.NET Identity is taking over and changing it to a 302.
How do I control which parts of my site are to be controlled by Identity? I can't use
<location path="Api"><system.web><authorization><allow users="*" /></authorization></system.web></location>
I know Identity is still fairly new, but I find it very odd that there's no way to control which part of an MVC site need to be authenticated. AllowAnonymousAttribute isn't appropriate as I don't want anonymous access to the controllers, just an authentication mechanism for the API controllers that's different from that of the MVC controllers.