gpt4 book ai didi

reactjs - 如何在 api (asp.net api) 中对通过 spa(react 应用程序)从 azure ad b2c 获取的访问 token 进行身份验证?

转载 作者:行者123 更新时间:2023-12-02 06:37:23 26 4
gpt4 key购买 nike

I have a react app as my client app and an asp.net api as my api (resources). I have managed to integrate azure ad b2c login in my client app. Now I am traying to send a request that contains the access token, to my api(which is now secured with azure ad b2c) to have access to my api resources. But I get status code 401 from the api that means unauthorized. I send the access token (bearer token) from client app (react) to the api like this:

         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": "*"

}

我的 Controller 如下所示:

    [Authorize]
[Route("[Controller]")]
[RequiredScope("user.read", "user.write")]
[ApiController]

public class TokenController : Controller
{
[HttpPost]
public async Task<IActionResult> Func([FromBody] CreateModel model)
{
some functions...
}

}

我应该说我可以在客户端应用程序中看到访问 token ( react )。为什么向 api 发送请求后会收到状态代码 401?我的代码有问题吗?我真的很感谢任何帮助:)

最佳答案

您似乎正在尝试访问 Microsoft Graph API,而不是后端 api。 (因为您的范围是:“User.Read”,这只不过是 microsoft graph api 的范围)。

您的前端应用程序需要使用 API 的范围,而不是 User.Read。这样它将获得一个用于您的 API 的访问 token 。通过“公开 API”部分为您的 API 应用程序注册注册一个范围,并在您的前端应用程序中使用该范围。

enter image description here

<小时/>

enter image description here

<小时/>

看起来怎么样

enter image description here

Note :Remove user.read permission which is for microsoft graph api.

关于reactjs - 如何在 api (asp.net api) 中对通过 spa(react 应用程序)从 azure ad b2c 获取的访问 token 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71143851/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com