AuthorizeFilter should always set default identity

This commit is contained in:
Hao Kung 2015-05-13 16:39:35 -07:00
parent 8ec28463fc
commit 1ea1cc4338
2 changed files with 22 additions and 1 deletions

View File

@ -44,6 +44,11 @@ namespace Microsoft.AspNet.Mvc
newPrincipal.AddIdentities(result.Identities);
}
}
// If all schemes failed authentication, provide a default identity anyways
if (newPrincipal.Identity == null)
{
newPrincipal.AddIdentity(new ClaimsIdentity());
}
context.HttpContext.User = newPrincipal;
}

View File

@ -9,7 +9,6 @@ using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.AspNet.Routing;
using Microsoft.AspNet.WebUtilities;
using Microsoft.Framework.DependencyInjection;
using Moq;
using Xunit;
@ -87,6 +86,22 @@ namespace Microsoft.AspNet.Mvc.Test
Assert.Null(authorizationContext.Result);
}
[Fact]
public async Task Invoke_AuthSchemesFailShouldSetEmptyPrincipalOnContext()
{
// Arrange
var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder("Fails")
.RequireAuthenticatedUser()
.Build());
var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());
// Act
await authorizeFilter.OnAuthorizationAsync(authorizationContext);
// Assert
Assert.NotNull(authorizationContext.HttpContext.User?.Identity);
}
[Fact]
public async Task Invoke_SingleValidClaimShouldSucceed()
{
@ -303,6 +318,7 @@ namespace Microsoft.AspNet.Mvc.Test
httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider);
auth.Setup(c => c.AuthenticateAsync("Bearer")).ReturnsAsync(new AuthenticationResult(bearerPrincipal, new AuthenticationProperties(), new AuthenticationDescription()));
auth.Setup(c => c.AuthenticateAsync("Basic")).ReturnsAsync(new AuthenticationResult(basicPrincipal, new AuthenticationProperties(), new AuthenticationDescription()));
auth.Setup(c => c.AuthenticateAsync("Fails")).ReturnsAsync(null);
// AuthorizationContext
var actionContext = new ActionContext(