Skip to content

Can you create authorization policies without using magic strings? #2947

@shaulbehr

Description

@shaulbehr

In this article I see that you declare your authorization policy using a magic string:

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

And then you tag your controller/endpoint with:

[Authorize(Policy = "AtLeast21")]

So, let's say I have multiple endpoints, with different age requirements for each. Do I then need to declare a separate policy for each age cutoff?

...
options.AddPolicy("AtLeast18", policy =>
    policy.Requirements.Add(new MinimumAgeRequirement(18)));
options.AddPolicy("AtLeast19", policy =>
    policy.Requirements.Add(new MinimumAgeRequirement(19)));
options.AddPolicy("AtLeast20", policy =>
    policy.Requirements.Add(new MinimumAgeRequirement(20)));
options.AddPolicy("AtLeast21", policy =>
    policy.Requirements.Add(new MinimumAgeRequirement(21)));
...

That's really not going to be the answer, is it...? I mean, I could obviously write a loop to add policies for every age between 1 and 120, but what happens if my AuthenticationRequirement has more than one variable? Are we going to write a quadruple-nested loop for my requirement that has four variables, so I can declare distinct policies for each one? And what if my policy takes a double as a parameter?

Please, tell me I've misunderstood how this works.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions