Hello @Jony Jahedur Rahman
The 401 error typically indicates an issue with the configuration of your ASP.NET Core Web API to properly validate the JWT token. Here are some steps and resources that might help you resolve this issue and ensure your applications are correctly configured:
Step-by-Step Guide
Register Applications in Azure AD:
- Register two applications in Azure AD: one for the Angular SPA and one for the ASP.NET Core Web API.
- Ensure that the Web API app is exposed with the necessary scopes and permissions.
Configure the Angular Application:
- Use MSAL.js to handle authentication and acquire tokens.
- Ensure that the acquired token includes the correct audience and scope for your Web API.
- Configure the ASP.NET Core Web API:
- Install the necessary NuGet packages:
Microsoft.Identity.Web
andMicrosoft.Identity.Web.UI
. - Configure the authentication middleware in
Startup.cs
orProgram.cs
:
Add Authorization to Controllers:services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(Configuration.GetSection(
- Use the
[Authorize]
attribute to protect your API endpoints.
- Use the
- Install the necessary NuGet packages:
Tutorials and Resources
- Microsoft Learn: Create an ASP.NET Core app with Angular - This tutorial covers creating an ASP.NET Core project with Angular and includes steps for setting up authentication.
- YouTube Tutorial: Azure Authentication Web App - Angular - This video provides a step-by-step guide on implementing Azure AD authentication in an Angular SPA and ASP.NET Core Web API.
- Hands-On Lab: Build a Single Page Application (SPA) with ASP.NET Web API and Angular.js - Although this is for an older version, the concepts are still relevant.
Common Pitfalls
- Token Audience: Ensure the token audience (
aud
) matches the API’s application ID URI. - CORS Issues: Make sure CORS is properly configured in your Web API to allow requests from your Angular app.
- Scopes and Permissions: Verify that the scopes requested by the Angular app match those exposed by the Web API.
If you follow these steps and refer to the provided resources, you should be able to resolve the 401 error and successfully authenticate and authorize users across your Angular SPA and ASP.NET Core Web API.
I hope that this response has addressed your query and helped you overcome your challenges. If so, please mark this response as Answered. This will not only acknowledge our efforts, but also assist other community members who may be looking for similar solutions.