Reputation: 33
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
Reputation: 23111
Regarding the issue, please refer to the following steps
Navigate to the Microsoft identity platform for developers App registrations page.
Select New registration.
When the Register an application page appears, enter your application's registration information:
ProfileAPI
.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.
Select the Expose an API section, and:
api://{clientId}
).access_as_user
Access ProfileAPI as a user
Accesses the ProfileAPI web API as a user
ProfileSPA
.http://localhost:3000
.ProfileAPI
API, or the name you entered for the web APIRegarding how to configure Azure AD in react application, please refer to here
{
"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
}
Install package Microsoft.Identity.Web
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