简体   繁体   中英

How to Validate appid of the Azure AD Access

We have a .NET Core application which performs JWT token authentication. This application is registered in Azure AD with a client Id of abcde and an API scope of api://abcde . Our tenant has other applications registered, one of which has a client id of fghij . What I noticed is that if I use this client Id with its secret and API scope api://abcde I was able to generate an access token and access the APIs under this scope.

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = $"{ Configuration.GetValue<string>("AzureAD:Instance") }/{ Configuration.GetValue<string>("AzureAD:TenantId") }/";
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidAudience = Configuration.GetValue<string>("AzureAD:Audience"),
        ValidIssuer = $"https://sts.windows.net/{ Configuration.GetValue<string>("AzureAD:TenantId") }"
    };
});

The solution I have in mind is to validate the appid field in the access token. How can I achieve this? Basically I want to make sure that only client Id abcde can request for an access token for scope api://abcde .

"aio": "abcde=",
"appid": "abcde", //client id of the application in Azure AD
"appidacr": "1",

You can get ClaimsPrincipal first and then use

ClaimsPrincipal.Current.FindFirst("appid").Value

to get the value of appid field. Then judge if the value equal to your specified app id.

You can change the default Authorization policy to validate appid claim. Out of the box, the default policy is:

new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .Build();

You can change it to:

    builder.Services.AddAuthorization(options =>
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .RequireClaim("appid", "allowedApp1", "allowedApp2")
            .Build();
    });

Please see for reference Setting global authorization policies using the DefaultPolicy and the FallbackPolicy in ASP.NET Core 3.x

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM