MediatR.Behaviors.Authorization 12.2.0

dotnet add package MediatR.Behaviors.Authorization --version 12.2.0                
NuGet\Install-Package MediatR.Behaviors.Authorization -Version 12.2.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MediatR.Behaviors.Authorization" Version="12.2.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MediatR.Behaviors.Authorization --version 12.2.0                
#r "nuget: MediatR.Behaviors.Authorization, 12.2.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MediatR.Behaviors.Authorization as a Cake Addin
#addin nuget:?package=MediatR.Behaviors.Authorization&version=12.2.0

// Install MediatR.Behaviors.Authorization as a Cake Tool
#tool nuget:?package=MediatR.Behaviors.Authorization&version=12.2.0                

MediatR.Behaviors.Authorization

NuGet

A simple request authorization package that allows you to build and run request specific authorization requirements before your request handler is called. You can read my article on the reasoning for this library for further analysis.

Installation

Using the .NET Core command-line interface (CLI) tools:

dotnet add package MediatR.Behaviors.Authorization

Using the NuGet Command Line Interface (CLI):

nuget install MediatR.Behaviors.Authorization

Using the Package Manager Console:

Install-Package MediatR.Behaviors.Authorization

From within Visual Studio:

  1. Open the Solution Explorer.
  2. Right-click on a project within your solution.
  3. Click on Manage NuGet Packages...
  4. Click on the Browse tab and search for "MediatR.Behaviors.Authorization".
  5. Click on the MediatR.Behaviors.Authorization package, select the latest version in the right-tab and click Install.

Getting Started

Dependency Injection

You will need to register the authorization pipeline along with all implementations of IAuthorizer:

using MediatR.Behaviors.Authorization.Extensions.DependencyInjection;

public class Startup
{
	//...
	public void ConfigureServices(IServiceCollection services)
	{
		// Adds the transient pipeline behavior and additionally registers all `IAuthorizationHandlers` for a given assembly
		services.AddMediatorAuthorization(Assembly.GetExecutingAssembly());
		// Register all `IAuthorizer` implementations for a given assembly
		services.AddAuthorizersFromAssembly(Assembly.GetExecutingAssembly())

	}
}

You can use the helper method to register 'IAuthorizer' implementations from an assembly or manually inject them using Microsoft's DI methods.

Example Usage

Scenario: We need to get details about a specific video for a course on behalf of a user. However, this video course information is considered privileged information and we only want users with a subscription to that course to have access to the information about the video.

Creating an Authorization Requirement IAuthorizationRequirement

Location: ~/Application/Authorization/MustHaveCourseSubscriptionRequirement.cs

You can create custom, reusable authorization rules for your MediatR requests by implementing IAuthorizationRequirement and IAuthorizationHandler<TAuthorizationRequirement>:

public class MustHaveCourseSubscriptionRequirement : IAuthorizationRequirement
    {
        public string UserId { get; set; }
        public int CourseId { get; set; }

        class MustHaveCourseSubscriptionRequirementHandler : IAuthorizationHandler<MustHaveCourseSubscriptionRequirement>
        {
            private readonly IApplicationDbContext _applicationDbContext;

            public MustHaveCourseSubscriptionRequirementHandler(IApplicationDbContext applicationDbContext)
            {
                _applicationDbContext = applicationDbContext;
            }

            public async Task<AuthorizationResult> Handle(MustHaveCourseSubscriptionRequirement request, CancellationToken cancellationToken)
            {
                var userId = request.UserId;
                var userCourseSubscription = await _applicationDbContext.UserCourseSubscriptions
                    .FirstOrDefaultAsync(x => x.UserId == userId && x.CourseId == request.CourseId, cancellationToken);

                if (userCourseSubscription != null)
                    return AuthorizationResult.Succeed();

                return AuthorizationResult.Fail("You don't have a subscription to this course.");
            }
        }
    }

In the preceding listing, you can see this is your standard MediatR Request/Request Handler usage; so you can treat the whole affair as you normally would. It is important to note you must return AuthorizationResult You can fail two ways: AuthorizationResult.Fail() or AuthorizationResult.Fail("your message here") and you can pass using AuthorizationResult.Succeed()

Basic MediatR Request

Location: ~/Application/Courses/Queries/GetCourseVideoDetail/GetCourseVideoDetailQuery.cs

public class GetCourseVideoDetailQuery : IRequest<CourseVideoDetailVm>
    {
        public int CourseId { get; set; }
        public int VideoId { get; set; }
        
        class GetCourseVideoDetailQueryHandler : IRequestHandler<GetCourseVideoDetailQuery>
        {
            private readonly IApplicationDbContext _applicationDbContext;

            public GetCourseVideoDetailQueryHandler(IApplicationDbContext applicationDbContext)
            {
                _applicationDbContext = applicationDbContext;
            }

            public async Task<CourseVideoDetailVm> Handle(GetCourseVideoDetailQuery request, CancellationToken cancellationToken)
            {
                var video = await _applicationDbContext.CourseVideos
                    .FirstOrDefaultAsync(x => x.CourseId == request.CourseId && x.VideoId == request.VideoId, cancellationToken);

                return new CourseVideoDetailVm(video);
            }
        }
    }

Creating the IAuthorizer

Location: ~/Application/Courses/Queries/GetCourseVideoDetail/GetCourseVideoDetailAuthorizer.cs

public class GetCourseVideoDetailAuthorizer : AbstractRequestAuthorizer<GetCourseVideoDetailQuery>
    {
        private readonly ICurrentUserService _currentUserService;

        public GetCourseVideoDetailAuthorizer(ICurrentUserService currentUserService)
        {
            _currentUserService = currentUserService;
        }

        public override void BuildPolicy(GetCourseVideoDetailQuery request)
        {
            UseRequirement(new MustHaveCourseSubscriptionRequirement
            {
                CourseId = request.CourseId,
                UserId = _currentUserService.UserId
            });
        }
    }

The usage of AbstractRequestAuthorizer<TRequest> will usually be preferable; this abstract class does a couple things for us. It takes care of initializing and adding new requirements to the Requirements property through the UseRequirement(IAuthorizationRequirement), finally, it still forces the class extending it to implement the IAuthorizer.BuildPolicy() method which is very important for passing the needed arguments to the authorization requirement that handles the authorization logic.

Overriding the Default Unauthorized Behavior

When a requirement is not met (i.e., IsAuthorized is false), the default behavior is to throw an UnauthorizedException. You can change this by creating a class which implements the Invoke method of the IUnauthorizedResultHandler interface:

public class ExampleUnauthorizedResultHandler : IUnauthorizedResultHandler
    {
        public Task<TResponse> Invoke<TResponse>(AuthorizationResult result)
        {
            return Task.FromResult(default(TResponse));
        }
    }

Once you have created your custom IUnauthorizedResultHandler, you will need to configure the options during IoC setup:

using MediatR.Behaviors.Authorization.Extensions.DependencyInjection;

public class Startup
{
	//...
	public void ConfigureServices(IServiceCollection services)
	{
		// Use the options overload method to configure your custom `IUnauthorizedResultHandler`
		services.AddMediatorAuthorization(Assembly.GetExecutingAssembly(), 
            cfg => cfg.UseUnauthorizedResultHandlerStrategy(new ExampleUnauthorizedResultHandler));
	}
}

The ExampleUnauthorizedResultHandler is a very basic example. Some reasons why you may want to override the default unauthorized behavior can include (but not limited to):

  • Throwing a different exception type
  • Attaching additional behavior such as raising an event.
  • If you are using a discriminated union library (e.g., OneOf, FluentResults, ErrorOr) in conjuction with your MediatR requests.

For any requests, bug or comments, please open an issue or submit a pull request.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on MediatR.Behaviors.Authorization:

Package Downloads
RedmentCore.MediatR

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
12.2.0 2,096 11/21/2024
12.1.1 54,218 10/20/2023
12.0.2 981 9/8/2023
12.0.1 13,685 3/15/2023
11.1.1 9,841 1/2/2023
11.1.0 2,579 12/10/2022
10.0.0 79,417 1/11/2022
1.2.0 19,096 3/1/2021
1.1.0 8,968 10/3/2020
1.0.3 4,831 10/3/2020
1.0.2 1,780 6/16/2020
1.0.1 496 6/16/2020
1.0.0 542 6/15/2020

Initial release