JJJCoder
JJJCoder

Reputation: 16986

The AuthorizationPolicy named: 'Admin' was not found

I am learning Authentication/Authorization in .NET Core MVC.

I am trying to create a controller that can only be accessed by 'Admin', but get the following error.

An unhandled exception occurred while processing the request.

InvalidOperationException: The AuthorizationPolicy named: 'Admin' was not found.

Here's my code. What should I do?

[HttpGet("~/Test")]
[Authorize("Admin")]
public async Task<string> MyMethod()
{
    return await Task<string>.Run(() => "Hello Admin");
}

Upvotes: 27

Views: 43801

Answers (3)

Maulik Boghara
Maulik Boghara

Reputation: 257

If you are using a Scheme-based authentication then you can pass the "AuthenticationSchemes "with authorize filter.

For example, [Authorize(AuthenticationSchemes = "UserBasicAuth")]

Here, your Startup.cs class should look like : AddScheme<AuthenticationSchemeOptions, ....>("UserBasicAuth", null)

Instead of, [Authorize(Policy = "UserBasicAuth")]

Upvotes: 1

JJJCoder
JJJCoder

Reputation: 16986

In line with the documentation here, you have not added the Authorization attribute correctly. This is the correct way to do it.

[HttpGet("~/Test")]
[Authorize(Roles ="Admin")]
public async Task<string> MyMethod()
{
    return await Task<string>.Run(() => "Hello Admin");
}

Upvotes: 35

Joe Audette
Joe Audette

Reputation: 36736

you can define the matching policy in Startup.cs

services.AddAuthorization(options =>
  {

        options.AddPolicy("Admin",
            authBuilder =>
            {
                authBuilder.RequireRole("Administrators");
            });

 });

the authBuilder has other methods on it, you can require claims or specific user names or custom rules using policy based authorization and control the rules from a central place in Startup https://docs.asp.net/en/latest/security/authorization/policies.html

Upvotes: 32

Related Questions