Mortalus
Mortalus

Reputation: 10712

How to set deaful Authorization in .net core 2

I am using a custom requirement like this:

    services.AddAuthorization(options => {
        options.AddPolicy("MyAuthorizationRequirement",policy => {
            policy.Requirements.Add(new MyRequirement());
        });
    });

I want to be able to set an [Authorize] attribute on my controller and use a custom authorization method.

but with the custom requirement i set i have to use [Authrization("MyAuthorizationRequirement")]

how can I set some sort of default to use just a single attribute ?

Upvotes: 0

Views: 542

Answers (2)

Jaliya Udagedara
Jaliya Udagedara

Reputation: 1196

Let me try to explain what is required here.

What services.AddAuthorization does is, it tries to configure authorization. Before configuring authorization first you need to configure authentication. For that in the ConfigureServices method, you can do something like this.

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => 
    {
        options.Audience = "http://localhost:5001/";
        options.Authority = "http://localhost:5000/";
    });

Now you can configure,

services
    .AddAuthorization(options =>
    {
        options.AddPolicy("PolicyName", policy => policy.RequireClaim("SomeClaimName"));
        // you can configure your requirement above in various ways, you might want to check those out
    });

And finally on the Configure method,

app.UseAuthentication();

So now in the controller,

// [Authorize("PolicyName")]
// If you have above in your controllers/actions, those will only be accessible to users who has "SomeClaimName"

// [Authorize]
// Those who are authenticated, can access these endpoints

Upvotes: 1

Kahbazi
Kahbazi

Reputation: 15015

You can create a new class which inherit from AuthorizeAttribute

public class MyAuthorizationAttribute : AuthorizeAttribute
{
    public MyAuthorizationAttribute()
        : base("MyAuthorizationRequirement")
    {
    }
}

and use [MyAuthorization] on your controllers.

Upvotes: 0

Related Questions