1

私はドキュメントhereおよびhereに従って、セキュリティへのクレームベースのアプローチを採用しています。ドキュメントのコードはコンパイルされません。

この行で

options.AddPolicy("Over21",
                          policy => policy.Requirements.Add(new Authorization.MinimumAgeRequirement(21)));
    });

コンパイル時エラーが発生します: The type MinimumAgeRequirementdoes not exist in the type これAuthorization がそのスクリーンショットです。

ここに画像の説明を入力

ここでより簡単な例に従おうとしている間

F5 を押すと、次のようなエラーが発生します。

ここに画像の説明を入力

どこかに完全に機能する例はありますか? ドキュメントは中途半端なようです。

4

1 に答える 1

2

これは、この例のために作成されたカスタム クラスであるためです。

リンクしたページにあります:

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 >= MinimumAge)
        {
            context.Succeed(requirement);
        }
    }
}

最終的なコードは次のようになります。

services.AddAuthorization(options =>
{
    options.AddPolicy("Over21",
                      policy => policy.Requirements.Add(new Authorization.MinimumAgeRequirement(21)));
});
services.AddInstance<IAuthorizationHandler>(new Authorization.MinimumAgeHandler());
于 2015-12-18T17:49:48.057 に答える