Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

AuthorizeFilter should always set a default identity #2552

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Microsoft.AspNet.Mvc.Core/Filters/AuthorizeFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ public virtual async Task OnAuthorizationAsync([NotNull] AuthorizationContext co
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;
}

Expand Down
15 changes: 15 additions & 0 deletions test/Microsoft.AspNet.Mvc.Core.Test/Filters/AuthorizeFilterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,20 @@ public async Task Invoke_EmptyClaimsShouldAuthorizeAuthenticatedUser()
Assert.Null(authorizationContext.Result);
}

[Fact]
public async Task Invoke_AuthSchemesFailShouldSetEmptyPrincipalOnContext()
{
// Arrange
var authorizeFilter = new AuthorizeFilter(new AuthorizationPolicyBuilder("Fails").RequireAuthenticatedUser().Build());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This crosses 120 character limit.

var authorizationContext = GetAuthorizationContext(services => services.AddAuthorization());

// Act
await authorizeFilter.OnAuthorizationAsync(authorizationContext);

// Assert
Assert.NotNull(authorizationContext.HttpContext.User?.Identity);
}

[Fact]
public async Task Invoke_SingleValidClaimShouldSucceed()
{
Expand Down Expand Up @@ -303,6 +317,7 @@ private AuthorizationContext GetAuthorizationContext(Action<ServiceCollection> r
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(
Expand Down