Middleware does not pass OwinContext.User forward in Pipeline · Issue #119 · aspnet/AspNetWebStack (original) (raw)
I am trying to setup a web api with signalr and during the process I noticed this oddity. I cannot seem to find a documented reason why the Identity on the OwinContext would be emptied out after there was no match on the web api route table. I put together a simple project to show this in action:
Startup
public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); config.Filters.Clear(); config.SuppressDefaultHostAuthentication(); appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationMode = AuthenticationMode.Active, AccessTokenFormat = new TokenFormatter(), AuthenticationType = "DummyAuth", Provider = new OAuthBearerAuthenticationProvider { OnValidateIdentity = async (ctx) => ctx.Validated(ctx.Ticket), OnRequestToken = async (ctx) => ctx.Token = "111" } }); appBuilder.Use("New Request", (Action)((IOwinContext ctx) => Console.WriteLine("End Request"))); appBuilder.UseCors(CorsOptions.AllowAll); appBuilder.Use("Before WebApi"); config.MapHttpAttributeRoutes(); appBuilder.UseWebApi(config); appBuilder.Use("After WebApi"); appBuilder.RunSignalR(); appBuilder.Use("After SignalR"); config.EnsureInitialized(); }
Dummy token formatter
public class TokenFormatter : ISecureDataFormat { public string Protect(AuthenticationTicket data) { return "111"; } public AuthenticationTicket Unprotect(string protectedText) { var identity = new ClaimsIdentity("DummyAuth"); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Bob")); identity.AddClaim(new Claim(ClaimTypes.Name, "Bob")); var ticket = new AuthenticationTicket(identity, null); return ticket; } }
Controller
[Authorize]
public class TestController : ApiController
{
[Route("Value")]
[HttpGet]
public string GetValue()
{
return "Hello World!";
}
}
Hub
public class TestHub : Hub
{
public override Task OnConnected()
{
Console.WriteLine($"Hub.OnConnected Username: {new OwinContext(Context.Request.Environment).Authentication?.User?.Identity?.Name}");
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
Console.WriteLine($"Hub.OnDisconnected Username: {new OwinContext(Context.Request.Environment).Authentication?.User?.Identity?.Name}");
return base.OnDisconnected(stopCalled);
}
}
If I attempt to connect to a Hub (at the end of the pipeline) the OwinContext is no longer authenticated.
The output from each DebugMiddleware shows:
Output
Start Request
Authenticated?: True
User: Bob
Before WebApi
Authenticated?: True
User: Bob
After WebApi
Authenticated?: False <- Why the change here?
User:
End Request
Is this a bug or is there a reason for this maddening quirk?