I’m afraid the issue comes from the auth configuration in startup. Pls allow me show my code snippet to explain it well.
In my opinion, you could use services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
instead. And you should exposed the api correctly.
The steps of exposing api, you can follow the documents. What I wanna repeat here is when you generate an access token, it should have the scope like api://clientid_of_the_app_exposed_api/tiny/User.Read
which can match the configuration in appsettings.json
My react code, it is referred to this sample:
import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";
const callApi = (accessToken) => {
const headers = new Headers();
const bearer = `Bearer ${accessToken}`;
headers.append("Authorization", bearer);
const options = {
method: "GET",
headers: headers
};
fetch("https://localhost:44341/api/home", options)
.then(response => {
var a = response.json();
console.log(a);
})
.catch(error => console.log(error));
};
const ProfileContent = () => {
const { instance , accounts} = useMsal();
const [graphData, setGraphData] = useState(null);
const loginRequest = {"scopes": ["api://clientid_of_the_app_exposed_api/tiny/User.Read"]};
function RequestProfileData() {
instance.acquireTokenSilent({
...loginRequest,
account: accounts[0]
}).then((response) => {
callApi(response.accessToken);
});
}
My ConfigureServices in startup file, these are referred to this document:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddControllers();
}
My appsettings :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"ClientId": "clientid_which_have_api_permission",
"Domain": "tenantname.onmicrosoft.com",
"TenantId": "common",
"Audience": "clientid_of_the_app_exposed_api"
}
}
My controller:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Identity.Web.Resource;
using System.Collections.Generic;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class HomeController : ControllerBase
{
[HttpGet]
[RequiredScope("User.Read")]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
}
}