创建一个使用服务的新AuthorizationHandler/IAuthorizationRequirement [英] Creating a new AuthorizationHandler/IAuthorizationRequirement that uses a service

查看:79
本文介绍了创建一个使用服务的新AuthorizationHandler/IAuthorizationRequirement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个新的Authorization要求,但是它必须使用我在ConfigureServices中声明的服务之一,而且我不知道如何以与声明服务相同的方法将该服务传递给新要求.

I am trying to create a new Authorization requirement, but it must use one of the services that I declare in ConfigureServices, and I have no idea how to pass that service to the new requirement in the same method as declaring the service.

public class NewRequirement: AuthorizationHandler<NewRequirement>, IAuthorizationRequirement
{
    private IRepository _repository;

    public NewRequirement(IRepository repository)
    {
        _repository = repository;
    }

    protected override void Handle(AuthorizationContext context, NewRequirement requirement)
    {
        //code that uses _repository here
    }
}

这很好,但是当我尝试在Startup.cs中添加策略时,如下所示:

This works fine, but when I try to add the policy in Startup.cs like this:

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddSingleton<RepositoryContext>();
        services.AddScoped<IRepository, Repository>();

        services.Configure<AuthorizationOptions>(options =>
        {
            options.AddPolicy("NewRequirement", policy => policy.Requirements.Add(new NewRequirement()));
        });
    }

我收到此错误

错误CS7036
没有给出与所需的形式参数'repository'相对应的参数'ExtraProjectRequirements.NewRequirement(IRepository)'
接收DNX 4.5.1

Error CS7036
There is no argument given that corresponds to the required formal parameter 'repository' of 'ExtraProjectRequirements.NewRequirement(IRepository)'
Reception.DNX 4.5.1

我认为我需要将IRepository传递给新策略,但是我不知道如何在ConfigureServices中进行操作.

I think I need to pass the IRepository to the new policy but I have no idea how to do it in ConfigureServices.

推荐答案

您正在将处理程序传递给需求,这是错误的. IAuthorizationRequirement AuthorizationHandler< NewRequirement> 必须是两个不同的类.另外, IAuthorizationRequirement 只是一个没有任何强制性属性或方法的标记接口,只是在此处偶然将任意类添加到Requirements集合中;)

You are passing the handler to the requirement, which is wrong. IAuthorizationRequirement and AuthorizationHandler<NewRequirement> need to be two distinct classes. Also IAuthorizationRequirement is only a marker interface w/o any mandatory properties or methods, just there to accidentally adding arbitrary classes to the Requirements collection ;)

IAuthorizationRequirement 将包含您的需求所需的纯数据(读取:无服务,无需注入依赖项),处理程序将对其进行验证.请参见 @blowdart 示例> Over18Requirement 及其处理程序以及官方文档.

The IAuthorizationRequirement will contain pure data (reads: No services, no dependencies that need to be injected) required for your requirement, the handler will validate it. See @blowdart example of an Over18Requirement and it's handler as well as the official documentation.

允许处理程序注入依赖项.

Handlers are allowed to have dependencies injected.

文档中的示例,供将来的读者使用(以防链接不可用).

Examples from the documentation for future readers (in case link becomes unavailable).

public class MinimumAgeRequirement : IAuthorizationRequirement
{
    public MinimumAgeRequirement(int age)
    {
        MinimumAge = age;
    }

    protected int MinimumAge { get; set; }
}

public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
{
    protected override void Handle(AuthorizationContext context, MinimumAgeRequirement requirement)
    {
        if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth &&
                                   c.Issuer == "http://contoso.com"))
        {
            return;
        }

        var dateOfBirth = Convert.ToDateTime(context.User.FindFirst(
            c => c.Type == ClaimTypes.DateOfBirth && c.Issuer == "http://contoso.com").Value);

        int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
        if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
        {
            calculatedAge--;
        }

        if (calculatedAge >= requirement.MinimumAge)
        {
            context.Succeed(requirement);
        }
    }
}

这篇关于创建一个使用服务的新AuthorizationHandler/IAuthorizationRequirement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆