Skip to content

Add FailureReasons #35425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
20 changes: 18 additions & 2 deletions src/Security/Authorization/Core/src/AuthorizationFailure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class AuthorizationFailure
private AuthorizationFailure() { }

/// <summary>
/// Failure was due to <see cref="AuthorizationHandlerContext.Fail"/> being called.
/// Failure was due to <see cref="AuthorizationHandlerContext.Fail()"/> being called.
/// </summary>
public bool FailCalled { get; private set; }

Expand All @@ -25,13 +25,29 @@ private AuthorizationFailure() { }
public IEnumerable<IAuthorizationRequirement> FailedRequirements { get; private set; } = Array.Empty<IAuthorizationRequirement>();

/// <summary>
/// Return a failure due to <see cref="AuthorizationHandlerContext.Fail"/> being called.
/// Allows <see cref="IAuthorizationHandler"/> to flow more detailed reasons for why authorization failed.
/// </summary>
public IEnumerable<AuthorizationFailureReason> Reasons { get; private set; } = Array.Empty<AuthorizationFailureReason>();

/// <summary>
/// Return a failure due to <see cref="AuthorizationHandlerContext.Fail()"/> being called.
/// </summary>
/// <returns>The failure.</returns>
public static AuthorizationFailure ExplicitFail()
=> new AuthorizationFailure
{
FailCalled = true
};

/// <summary>
/// Return a failure due to <see cref="AuthorizationHandlerContext.Fail(AuthorizationFailureReason)"/> being called.
/// </summary>
/// <returns>The failure.</returns>
public static AuthorizationFailure Failed(IEnumerable<AuthorizationFailureReason> reasons)
=> new AuthorizationFailure
{
FailCalled = true,
Reasons = reasons
};

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Authorization
{
/// <summary>
/// Encapsulates a reason why authorization failed.
/// </summary>
public class AuthorizationFailureReason
{
/// <summary>
/// Creates a new failure reason.
/// </summary>
/// <param name="handler">The handler responsible for this failure reason.</param>
/// <param name="message">The message describing the failure.</param>
public AuthorizationFailureReason(IAuthorizationHandler handler, string message)
{
Handler = handler;
Message = message;
}

/// <summary>
/// A message describing the failure reason.
/// </summary>
public string Message { get; set; }

/// <summary>
/// The <see cref="IAuthorizationHandler"/> responsible for this failure reason.
/// </summary>
public IAuthorizationHandler Handler { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ namespace Microsoft.AspNetCore.Authorization
public class AuthorizationHandlerContext
{
private readonly HashSet<IAuthorizationRequirement> _pendingRequirements;
private readonly List<AuthorizationFailureReason> _failedReasons;
private bool _failCalled;
private bool _succeedCalled;

Expand All @@ -37,6 +38,7 @@ public AuthorizationHandlerContext(
User = user;
Resource = resource;
_pendingRequirements = new HashSet<IAuthorizationRequirement>(requirements);
_failedReasons = new List<AuthorizationFailureReason>();
}

/// <summary>
Expand All @@ -59,6 +61,11 @@ public AuthorizationHandlerContext(
/// </summary>
public virtual IEnumerable<IAuthorizationRequirement> PendingRequirements { get { return _pendingRequirements; } }

/// <summary>
/// Gets the reasons why authorization has failed.
/// </summary>
public virtual IEnumerable<AuthorizationFailureReason> FailureReasons { get { return _failedReasons; } }

/// <summary>
/// Flag indicating whether the current authorization processing has failed.
/// </summary>
Expand All @@ -84,6 +91,20 @@ public virtual void Fail()
_failCalled = true;
}

/// <summary>
/// Called to indicate <see cref="AuthorizationHandlerContext.HasSucceeded"/> will
/// never return true, even if all requirements are met.
/// </summary>
/// <param name="reason">Optional <see cref="AuthorizationFailureReason"/> for why authorization failed.</param>
public virtual void Fail(AuthorizationFailureReason reason)
{
Fail();
if (reason != null)
{
_failedReasons.Add(reason);
}
}

/// <summary>
/// Called to mark the specified <paramref name="requirement"/> as being
/// successfully evaluated.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public AuthorizationResult Evaluate(AuthorizationHandlerContext context)
=> context.HasSucceeded
? AuthorizationResult.Success()
: AuthorizationResult.Failed(context.HasFailed
? AuthorizationFailure.ExplicitFail()
? AuthorizationFailure.Failed(context.FailureReasons)
: AuthorizationFailure.Failed(context.PendingRequirements));
}
}
10 changes: 10 additions & 0 deletions src/Security/Authorization/Core/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
#nullable enable
*REMOVED*static Microsoft.AspNetCore.Authorization.AuthorizationServiceExtensions.AuthorizeAsync(this Microsoft.AspNetCore.Authorization.IAuthorizationService! service, System.Security.Claims.ClaimsPrincipal! user, object! resource, Microsoft.AspNetCore.Authorization.IAuthorizationRequirement! requirement) -> System.Threading.Tasks.Task<Microsoft.AspNetCore.Authorization.AuthorizationResult!>!
Microsoft.AspNetCore.Authorization.AuthorizationFailure.Reasons.get -> System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Authorization.AuthorizationFailureReason!>!
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason.AuthorizationFailureReason(Microsoft.AspNetCore.Authorization.IAuthorizationHandler! handler, string! message) -> void
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason.Handler.get -> Microsoft.AspNetCore.Authorization.IAuthorizationHandler!
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason.Handler.set -> void
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason.Message.get -> string!
Microsoft.AspNetCore.Authorization.AuthorizationFailureReason.Message.set -> void
static Microsoft.AspNetCore.Authorization.AuthorizationFailure.Failed(System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Authorization.AuthorizationFailureReason!>! reasons) -> Microsoft.AspNetCore.Authorization.AuthorizationFailure!
static Microsoft.AspNetCore.Authorization.AuthorizationServiceExtensions.AuthorizeAsync(this Microsoft.AspNetCore.Authorization.IAuthorizationService! service, System.Security.Claims.ClaimsPrincipal! user, object? resource, Microsoft.AspNetCore.Authorization.IAuthorizationRequirement! requirement) -> System.Threading.Tasks.Task<Microsoft.AspNetCore.Authorization.AuthorizationResult!>!
virtual Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext.Fail(Microsoft.AspNetCore.Authorization.AuthorizationFailureReason! reason) -> void
virtual Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext.FailureReasons.get -> System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Authorization.AuthorizationFailureReason!>!
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,54 @@ public Task HandleAsync(AuthorizationHandlerContext context)
}
}

private class ReasonableFailHandler : IAuthorizationHandler
{
private string _reason;

public ReasonableFailHandler(string reason) => _reason = reason;

public bool Invoked { get; set; }

public Task HandleAsync(AuthorizationHandlerContext context)
{
Invoked = true;
context.Fail(new AuthorizationFailureReason(this, _reason));
return Task.FromResult(0);
}
}

[Fact]
public async Task CanFailWithReasons()
{
var handler1 = new ReasonableFailHandler("1");
var handler2 = new FailHandler();
var handler3 = new ReasonableFailHandler("3");
var authorizationService = BuildAuthorizationService(services =>
{
services.AddSingleton<IAuthorizationHandler>(handler1);
services.AddSingleton<IAuthorizationHandler>(handler2);
services.AddSingleton<IAuthorizationHandler>(handler3);
services.AddAuthorization(options =>
{
options.AddPolicy("Custom", policy => policy.Requirements.Add(new CustomRequirement()));
});
});

// Act
var allowed = await authorizationService.AuthorizeAsync(new ClaimsPrincipal(), "Custom");

// Assert
Assert.False(allowed.Succeeded);
Assert.NotNull(allowed.Failure);
Assert.Equal(2, allowed.Failure.Reasons.Count());
var first = allowed.Failure.Reasons.First();
Assert.Equal("1", first.Message);
Assert.Equal(handler1, first.Handler);
var second = allowed.Failure.Reasons.Last();
Assert.Equal("3", second.Message);
Assert.Equal(handler3, second.Handler);
}

[Fact]
public async Task Authorize_ShouldFailWhenAllRequirementsNotHandled()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Xunit;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Xunit;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Xunit;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Xunit;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Threading.Tasks;
using CustomAuthorizationFailureResponse.Authorization.Requirements;
using Microsoft.AspNetCore.Authorization;

namespace CustomAuthorizationFailureResponse.Authorization.Handlers
{
public class SampleWithFailureReasonRequirementHandler : AuthorizationHandler<SampleFailReasonRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SampleFailReasonRequirement requirement)
{
context.Fail(new AuthorizationFailureReason(this, "This is a way to provide more failure reasons."));
return Task.CompletedTask;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Authorization;

namespace CustomAuthorizationFailureResponse.Authorization.Requirements
{
public class SampleFailReasonRequirement : IAuthorizationRequirement
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ public async Task HandleAsync(
// if the authorization was forbidden, let's use custom logic to handle that.
if (policyAuthorizationResult.Forbidden && policyAuthorizationResult.AuthorizationFailure != null)
{
if (policyAuthorizationResult.AuthorizationFailure.Reasons.Any())
{
await httpContext.Response.WriteAsync(policyAuthorizationResult.AuthorizationFailure.Reasons.First().Message);

// return right away as the default implementation would overwrite the status code
return;
}

// as an example, let's return 404 if specific requirement has failed
if (policyAuthorizationResult.AuthorizationFailure.FailedRequirements.Any(requirement => requirement is SampleRequirement))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ public static class SamplePolicyNames
{
public const string CustomPolicy = "Custom";
public const string CustomPolicyWithCustomForbiddenMessage = "CustomPolicyWithCustomForbiddenMessage";
public const string FailureReasonPolicy = "FailureReason";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,12 @@ public string GetWithCustomPolicy()
{
return "Hello world from GetWithCustomPolicy";
}

[HttpGet("failureReason")]
[Authorize(Policy = SamplePolicyNames.FailureReasonPolicy)]
public string FailureReason()
{
return "Hello world from FailureReason";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,17 @@ public void ConfigureServices(IServiceCollection services)
{
options.AddPolicy(SamplePolicyNames.CustomPolicy, policy =>
policy.AddRequirements(new SampleRequirement()));

options.AddPolicy(SamplePolicyNames.FailureReasonPolicy, policy =>
policy.AddRequirements(new SampleFailReasonRequirement()));

options.AddPolicy(SamplePolicyNames.CustomPolicyWithCustomForbiddenMessage, policy =>
policy.AddRequirements(new SampleWithCustomMessageRequirement()));
});

services.AddTransient<IAuthorizationHandler, SampleRequirementHandler>();
services.AddTransient<IAuthorizationHandler, SampleWithCustomMessageRequirementHandler>();
services.AddTransient<IAuthorizationHandler, SampleWithFailureReasonRequirementHandler>();
services.AddTransient<IAuthorizationMiddlewareResultHandler, SampleAuthorizationMiddlewareResultHandler>();
}

Expand Down