![]() |
VOOZH | about |
dotnet add package MediatR.Behaviors.Authorization --version 12.5.0
NuGet\Install-Package MediatR.Behaviors.Authorization -Version 12.5.0
<PackageReference Include="MediatR.Behaviors.Authorization" Version="12.5.0" />
<PackageVersion Include="MediatR.Behaviors.Authorization" Version="12.5.0" />Directory.Packages.props
<PackageReference Include="MediatR.Behaviors.Authorization" />Project file
paket add MediatR.Behaviors.Authorization --version 12.5.0
#r "nuget: MediatR.Behaviors.Authorization, 12.5.0"
#:package MediatR.Behaviors.Authorization@12.5.0
#addin nuget:?package=MediatR.Behaviors.Authorization&version=12.5.0Install as a Cake Addin
#tool nuget:?package=MediatR.Behaviors.Authorization&version=12.5.0Install as a Cake Tool
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.
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:
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.
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.
IAuthorizationRequirementLocation: ~/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()
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);
}
}
}
IAuthorizerLocation: ~/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.
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):
For any requests, bug or comments, please open an issue or submit a pull request.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 was computed. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 netstandard2.0 is compatible. netstandard2.1 netstandard2.1 was computed. |
| .NET Framework | net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 1 NuGet packages that depend on MediatR.Behaviors.Authorization:
| Package | Downloads |
|---|---|
|
RedmentCore.MediatR
Package Description |
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 12.5.0 | 49,939 | 6/3/2025 |
| 12.2.0 | 118,000 | 11/21/2024 |
| 12.1.1 | 77,071 | 10/20/2023 |
| 12.0.2 | 1,297 | 9/8/2023 |
| 12.0.1 | 15,479 | 3/15/2023 |
| 11.1.1 | 10,487 | 1/2/2023 |
| 11.1.0 | 4,841 | 12/10/2022 |
| 10.0.0 | 98,651 | 1/11/2022 |
| 1.2.0 | 20,095 | 3/1/2021 |
| 1.1.0 | 10,540 | 10/3/2020 |
| 1.0.3 | 5,228 | 10/3/2020 |
| 1.0.2 | 2,096 | 6/16/2020 |
| 1.0.1 | 720 | 6/16/2020 |
| 1.0.0 | 863 | 6/15/2020 |
Initial release