amplifier
amplifier

Reputation: 1833

Azure AD and Group-based authorization with token in Web API

In my Azure AD I have user and group. I want to give an access to users according to a group the belong to.

I successfully implement it in ASP.NET MVC application. How I set up group claims:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddSpaStaticFiles(c => { c.RootPath = "ClientApp/dist";});

     services.AddAuthorization(options =>
    {
        options.AddPolicy("Admins",
            policyBuilder =>
            {
                policyBuilder.RequireClaim("groups",
                    Configuration.GetValue<string>("AzureSecurityGroup:AdminObjectId"));
            });
    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Employees",
            policyBuilder =>
            {
                policyBuilder.RequireClaim("groups",
                    Configuration.GetValue<string>("AzureSecurityGroup:EmployeeObjectId"));
            });
    });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("Managers",
            policyBuilder => policyBuilder.RequireClaim("groups", Configuration.GetValue<string>("AzureSecurityGroup:ManagerObjectId")));
    });

    services.Configure<AzureADOptions>(Configuration.GetSection("AzureAd"));
}

And if I want to restrict access for non-admin user to Contacts page I do this:

public class HomeController : Controller
{
    [Authorize(Policy = "Admins")]
    public IActionResult Contact()
    {
        ViewData["Message"] = "Your contact page.";

        return View();
    }
}

It works Now the idea is to create an web api controller and restrict access to some of the method.

//[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] {"value1", "value2"};
    }

    // GET api/values/5
    [Authorize(Policy = "Admins")]
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return "value";
    }
}

I use postman. I get an access token:

POST https://login.microsoftonline.com/{tenant_id}/oauth2/token

then send

GET https://localhost/api/values/1

with header Authorization and value Bearer {token} but get Unauthorized access (401). (Unprotected https://localhost/api/values works as expected though). I suspect that I pass wrong token, I check it on https://jwt.io/ and it does not contain information about a group the user belongs to. Should I configure it in the code another way? Thanks

Update 1 (decoded token):

{
  "typ": "JWT",
  "alg": "RS256",
  "x5t": "nbCwW11w3XkB-xUaXwKRSLjMHGQ",
  "kid": "nbCwW11w3XkB-xUaXwKRSLjMHGQ"
}.{
  "aud": "00000002-0000-0000-c000-000000000000",
  "iss": "https://sts.windows.net/xxxxxxxx-1835-453d-a552-28feda08393e/",
  "iat": 1544770435,
  "nbf": 1544770435,
  "exp": 1544774335,
  "aio": "42RgYPjkVuw2Z/fJtp+RF/mUp7Z5AQA=",
  "appid": "963418bb-8a31-4c47-bc91-56b6e51181dc",
  "appidacr": "1",
  "idp": "https://sts.windows.net/xxxxxxxx-1835-453d-a552-28feda08393e/",
  "oid": "0dfb0f07-b6e1-4318-ba33-066e1fc3c0ac",
  "sub": "0dfb0f07-b6e1-4318-ba33-066e1fc3c0ac",
  "tenant_region_scope": "EU",
  "tid": "xxxxxxxx-1835-453d-a552-28feda08393e",
  "uti": "cxlefO0ABkimo2z-7L0IAA",
  "ver": "1.0"
}.[Signature]

Upvotes: 0

Views: 2278

Answers (1)

Nan Yu
Nan Yu

Reputation: 27528

When using grant_type is client_credentials , that means you are using the client credentials flow to acquire access token for accessing the resource :

https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow

The OAuth 2.0 Client Credentials Grant Flow permits a web service (confidential client) to use its own credentials instead of impersonating a user, to authenticate when calling another web service. In this scenario, the client is typically a middle-tier web service, a daemon service, or web site.

In this scenario , the client use its own credentials instead of impersonating a user , no user information/identity is included in this scenario. You should use Code Grant Flow to authorize access to web applications and web APIs using user's identity :

https://learn.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code

Upvotes: 1

Related Questions