Update Authz Handlers DI to 6.0 (#25417)

pull/25419/head
Kirk Larkin 2022-03-25 10:36:32 +00:00 committed by GitHub
parent 37632e461a
commit 5ee8112c64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 69 additions and 24 deletions

View File

@ -2,47 +2,92 @@
title: Dependency injection in requirement handlers in ASP.NET Core
author: rick-anderson
description: Learn how to inject authorization requirement handlers into an ASP.NET Core app using dependency injection.
monikerRange: ">= aspnetcore-2.1"
ms.author: riande
ms.date: 10/14/2016
ms.date: 03/25/2022
no-loc: ["Blazor Hybrid", Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR]
uid: security/authorization/dependencyinjection
---
# Dependency injection in requirement handlers in ASP.NET Core
<a name="security-authorization-di"></a>
:::moniker range=">= aspnetcore-6.0"
[Authorization handlers must be registered](xref:security/authorization/policies#security-authorization-policies-based-handler-registration) in the service collection during configuration using [dependency injection](xref:fundamentals/dependency-injection).
Suppose you had a repository of rules you wanted to evaluate inside an authorization handler and that repository was registered in the service collection. Authorization resolves and injects that into the constructor.
For example, to use ASP.NET's logging infrastructure, inject `ILoggerFactory` into the handler. Such a handler might look like the following code:
For example, to use the .NET logging infrastructure, inject <xref:Microsoft.Extensions.Logging.ILoggerFactory> into the handler, as shown in the following example:
```csharp
public class LoggingAuthorizationHandler : AuthorizationHandler<MyRequirement>
{
ILogger _logger;
public class SampleAuthorizationHandler : AuthorizationHandler<SampleRequirement>
{
private readonly ILogger _logger;
public LoggingAuthorizationHandler(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger(this.GetType().FullName);
}
public SampleAuthorizationHandler(ILoggerFactory loggerFactory)
=> _logger = loggerFactory.CreateLogger(GetType().FullName);
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
_logger.LogInformation("Inside my handler");
// Check if the requirement is fulfilled.
return Task.CompletedTask;
}
}
```
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, SampleRequirement requirement)
{
_logger.LogInformation("Inside my handler");
// ...
The preceding handler can be registered with any [service lifetime](/dotnet/core/extensions/dependency-injection#service-lifetimes). The following code uses `AddSingleton` to register the preceding handler:
```csharp
services.AddSingleton<IAuthorizationHandler, LoggingAuthorizationHandler>();
return Task.CompletedTask;
}
}
```
An instance of the handler is created when the app starts, and DI injects the registered `ILoggerFactory` into the constructor.
The preceding handler can be registered with any [service lifetime](/dotnet/core/extensions/dependency-injection#service-lifetimes). The following code uses <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton%2A> to register the preceding handler:
```csharp
builder.Services.AddSingleton<IAuthorizationHandler, SampleAuthorizationHandler>();
```
An instance of the handler is created when the app starts, and DI injects the registered `ILoggerFactory` into its constructor.
> [!NOTE]
> Handlers that use Entity Framework shouldn't be registered as singletons.
> Don't register authorization handlers that use Entity Framework (EF) as singletons.
:::moniker-end
:::moniker range="< aspnetcore-6.0"
[Authorization handlers must be registered](xref:security/authorization/policies#security-authorization-policies-based-handler-registration) in the service collection during configuration using [dependency injection](xref:fundamentals/dependency-injection).
Suppose you had a repository of rules you wanted to evaluate inside an authorization handler and that repository was registered in the service collection. Authorization resolves and injects that into the constructor.
For example, to use the .NET logging infrastructure, inject <xref:Microsoft.Extensions.Logging.ILoggerFactory> into the handler, as shown in the following example:
```csharp
public class SampleAuthorizationHandler : AuthorizationHandler<SampleRequirement>
{
private readonly ILogger _logger;
public SampleAuthorizationHandler(ILoggerFactory loggerFactory)
=> _logger = loggerFactory.CreateLogger(GetType().FullName);
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context, SampleRequirement requirement)
{
_logger.LogInformation("Inside my handler");
// ...
return Task.CompletedTask;
}
}
```
The preceding handler can be registered with any [service lifetime](/dotnet/core/extensions/dependency-injection#service-lifetimes). The following code uses <xref:Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton%2A> to register the preceding handler:
```csharp
services.AddSingleton<IAuthorizationHandler, SampleAuthorizationHandler>();
```
An instance of the handler is created when the app starts, and DI injects the registered `ILoggerFactory` into its constructor.
> [!NOTE]
> Don't register authorization handlers that use Entity Framework (EF) as singletons.
:::moniker-end