我创建了一个 API 并期待来自 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"]}";
});
然后我使用 MSAL 在 React 上创建了一个 SPA,但是当我登录时,我的 API 不接受从 MSAL 返回的访问令牌:
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)
});
})
我的 MSAL 配置是:
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']
}
答案 0 :(得分:0)
关于问题,请参考以下步骤
导航到 Microsoft 开发人员标识平台 App registrations 页面。
选择新注册。
当出现注册应用程序页面时,输入应用程序的注册信息:
ProfileAPI
。在应用概览页面上,找到应用(客户端)ID值并记录下来以备后用。您将需要它来配置此项目的配置文件。
选择公开 API 部分,然后:
api://{clientId}
的形式)。access_as_user
Access ProfileAPI as a user
Accesses the ProfileAPI web API as a user
ProfileSPA
。http://localhost:3000
。ProfileAPI
API 或您为 Web API 输入的名称关于如何在react应用中配置Azure AD,请参考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
}
安装包 Microsoft.Identity.Web
更新 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();
});
}
}