Mer Merced
Mer Merced

Reputation: 33

Azure AD Authentication Token not authorized

I created an API and am expecting an access token from Azure AD:

services.AddMvc(options =>
        {
            var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();

            options.Filters.Add(new AuthorizeFilter(policy));

        }).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);


        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Audience = Configuration["AzureAd:ClientId"];
                options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";

            });

Then I created a SPA on React using MSAL, but when I login the access token returned from MSAL is not accepted on my API:

function RequestProfileData() {
   
    instance.acquireTokenSilent({
        ...loginRequest,
        account: accounts[0]
    }).then((response) => {
        debugger;
        const api = axios.create({
            baseURL: 'https://localhost:44312',
            headers: {
                authorization: `Bearer ${response.accessToken}`
            }
        });
        
        
        api.get('/WeatherForecast').then(result => {
            debugger;
            console.log(result.data)
        });
    
    })

My MSAL configuration is:

export const msalConfig = {
    auth: {
        clientId: "ClientId",
        authority: "https://sts.windows.net/TenantId/",
        tenantId: "TenantId",
        redirectUri: "http://localhost:3000/",
            "
    },
    cashe: {
        casheLocation: "sessionStorage",
        storeAuthStateInCookkie: false
    },
}

export const loginRequest = {
    scope: ['api://ClientId/Read']
}

Upvotes: 1

Views: 1461

Answers (1)

Jim Xu
Jim Xu

Reputation: 23111

Regarding the issue, please refer to the following steps

Register the service in Azure AD

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. When the Register an application page appears, enter your application's registration information:

    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example ProfileAPI.
    • Change Supported account types to Personal Microsoft accounts only.
    • Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the configuration file for this projects.

  5. Select the Expose an API section, and:

    • Click Set next to the Application ID URI to generate a URI that is unique for this app (in the form of api://{clientId}).
    • Select Add a scope
    • Enter the following parameters
      • for Scope name use access_as_user
      • Keep Admins and users for Who can consent
      • in User consent display name type Access ProfileAPI as a user
      • in User consent description type Accesses the ProfileAPI web API as a user
      • Keep State as Enabled
      • Select Add scope

Register the client

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. When the Register an application page appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example ProfileSPA.
    • Change Supported account types to Accounts in this organizational directory only.
    • Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the configuration file for this projects.
  5. From the app's Overview page, select the Authentication section.
    • Click Add a platform button.
    • Select Single-page Applications on the right blade.
    • Add a Redirect URIs, for instance http://localhost:3000.
    • Click Configure.
  6. Select the API permissions section
    • Click the Add a permission button and then,
    • Ensure that the My APIs tab is selected
    • In the list of APIs, select the ProfileAPI API, or the name you entered for the web API
    • In the Delegated permissions section, ensure that the right permissions are checked: access_as_user. Use the search box if necessary.
    • Select the Add permissions button.

Configure Client Application

Regarding how to configure Azure AD in react application, please refer to here

Configure Server application

  1. Update appsetting.json
{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "[Client_id-of-web-api-eg-2ec40e65-ba09-4853-bcde-bcb60029e596]",
    "TenantId": "common",
    "Audience": "custom App ID URI for your web API"
  },
  // more lines
}
  1. Install package Microsoft.Identity.Web

  2. Update startup.cs

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                // Since IdentityModel version 5.2.1 (or since Microsoft.AspNetCore.Authentication.JwtBearer version 2.2.0),
                // PII hiding in log files is enabled by default for GDPR concerns.
                // For debugging/development purposes, one can enable additional detail in exceptions by setting IdentityModelEventSource.ShowPII to true.
                // Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

For more details, please refer to here and here

Upvotes: 1

Related Questions