我有一個反應應用程式作為我的客戶端應用程式和一個 asp.net api 作為我的 api(資源)。我已經設法在我的客戶端應用程式中集成了 azure ad b2c 登錄。現在我正在準備向我的 api(現在使用 azure ad b2c 保護)發送一個包含訪問令牌的請求,以訪問我的 api 資源。但我從 api 獲得狀態碼 401,這意味著未經授權。我將訪問令牌(承載令牌)從客戶端應用程式(反應)發送到 api,如下所示:
const tokenItem = sessionStorage.getItem('item1');
const tokenjson = JSON.parse(tokenItem);
const accessToken = tokenjson.secret;
const tokenConfig = {
headers: { Authorization: `Bearer ${accessToken}` }
};
axios.post('https://localhost:44304/func', model, tokenConfig)
.then(response => {
this.setState({ Result: response.data });
})
.catch(error => {
console.log(error)
})
在 api 應用程式中,我在 Startup.cs 中有以下代碼
public void ConfigureServices(IServiceCollection services)
{
...
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { Configuration.Bind("AzureAdB2C", options); });
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseAuthentication();
app.UseAuthorization();
...
}
我在 api 應用程式中的 appsettings.json 是這樣的:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AzureAdB2C": {
"Instance": "https://mytenantName.b2clogin.com",
"Domain": "mytenantName.onmicrosoft.com",
"ClientId": "my api client id ",
"SignUpSignInPolicyId": "B2C_1_mySignupSignin_userflow"
},
"AllowedHosts": "*"
}
我的控制器如下所示:
[Authorize]
[Route("[Controller]")]
[RequiredScope("user.read", "user.write")]
[ApiController]
public class TokenController : Controller
{
[HttpPost]
public async Task<IActionResult> Func([FromBody] CreateModel model)
{
some functions...
}
}
我應該說我可以在客戶端應用程式中看到訪問令牌(反應)。為什么我向api發送請求后得到狀態碼401?我的代碼有問題嗎?我真的很感激任何幫助:)
uj5u.com熱心網友回復:
看起來您正在嘗試訪問 Microsoft Graph API 而不是后端 api。(因為您的范圍是 :"User.Read" 這不過是 microsoft graph api 的范圍)。
您的前端應用程式需要為您的 API 使用范圍,而不是 User.Read。這樣,它將獲得一個用于您的 API 的訪問令牌。通過公開 API 部分為您的 API 應用注冊注冊一個范圍,并在您的前端應用中使用該范圍。


它看起來如何

注意:洗掉用于 microsoft graph api 的 user.read 權限。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/426224.html
標籤:反应 天蓝色 asp.net-web-api 天蓝色广告 b2c
上一篇:KQL中的自定義日期格式
