简体   繁体   中英

Securing ASP.NET Core Web API with Azure AD

I am trying to start a new project that uses Azure AD for authentication. It is set up so that I have a SPA on the front end that gets information from an ASP.NET core web API, both of which I am creating. I am having trouble getting the front end token to authorize in the API. Every time I send a request to the API I get the error: Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10231: Audience validation failed .

I have set up the project as following.

In Azure AD I have set up two applications: One for the front end and one for the API. The API application has an API exposed called access_as_user . The front end application then has access to this. I have also made a client secret for both and added redirect URL's for the front end.

In my ASP.NET core API I am using I'm using Microsoft.Identity.Web and calling it like so:

// startup.cs

...
public void ConfigureServices(IServiceCollection services)
  {
    ...
    services.AddProtectedWebApi(Configuration, subscribeToJwtBearerMiddlewareDiagnosticsEvents: true);
    ...
  }
...

In my config the values are as follows:

"AzureAD": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "mydomain.onmicrosoft.com",
    "TenantId": "*MY TENANT ID*",
    "ClientId": "*Client ID of API",
    "ClientSecret": "Client Secret for API",
    "Audience": "Client ID of Front End"
}

To get auth I followed this tutorial -> here <- to set up PostMan to use OAuth 2.0 and get the tokens for me automatically. The magic happens at the end of step 3 in the tutorial.

Any help would be greatly appreciated.

Edit: After following the tutorial like alphaz18 suggested, I found my issue. I had forgotten to add the Authentication middle ware in the Configure part of Startup.cs .

            app.UseRouting();
            app.UseAuthentication(); // This line was missing.
            app.UseAuthorization();

I would highly recommend you follow the Microsoft sample tutorials first as they are all working. they give you all steps to get these samples working and is a great place to start: https://github.com/Azure-Samples/ms-identity-javascript-angular-spa-aspnetcore-webapi

in that tutorial you posted, I don't see anything about audience either. So where did you get that from?

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