3

Owin middleware implementations lookup their own authentication type before adding a challenge, so only the appropriate middleware responds. Multiple challenges can be used at the same time.

protected override Task ApplyResponseChallengeAsync()
{
    if (Response.StatusCode == 401)
    {
        var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);

        if (challenge != null)
        {
            Response.Headers.AppendValues("WWW-Authenticate", _challenge);
        }
    }

    return Task.FromResult<object>(null);
}

When using the built-in Cookie or Bearer middleware, the "Bearer" type is always present and gets looked up.

Where would I add my own challenge type globally so it gets looked up? This can be done manually within a request context by calling

Request.GetOwinContext().Authentication.Challenge("Basic");

but I would like to add a global configuration for all controllers.

Benjamin E.
  • 5,042
  • 5
  • 38
  • 65

1 Answers1

1

You can set AuthenticationResponseChallenge using AuthenticationManager.Challenge() methods. For example, in your startup.cs, you can have something like context.Authentication.Challenge(new AuthenticationProperties(), Options.AuthenticationType), so that the middleware that corresponds to Options.AuthenticationType gets back this challenge when looking up.

Active middleware will try to handle all the outgoing challenges irrespective of its AuthenticationType. Usually, only the cookie middleware is set to active and all other middleware are passive. For a passive middleware to act on a challenge, the challenge should have the matching AuthenticationType.

ezile
  • 571
  • 2
  • 6
  • 20
  • So when I add the challenge to the AuthenticationManager in Startup.cs, `Microsoft.Owin.Security.Infrastructure.SecurityHelper.LookupChallenge` will return the challenge in my middleware, right? – Benjamin E. Jul 18 '15 at 03:15
  • How do you get access to AuthenticationManager in Startup.cs? I can't find the namespaces/classes. – Benjamin E. Jul 18 '15 at 06:31
  • `context.Authentication.Challenge()`. context is of type HttpContext and should be availave in your startup.cs or controller. Authentication property is of type AuthenticationManager. – ezile Jul 19 '15 at 04:14
  • Trying `HttpContext.Current.GetOwinContext().Authentication.Challenge("Basic")` in Startup.cs throws "No owin.Environment item was found in the context." which doesn't surprise me because Startup.cs runs outside of a request-context. – Benjamin E. Jul 20 '15 at 02:37