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

标签 reactjs azure asp.net-web-api azure-ad-b2c

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/

相关文章:

azure - 如何将 Azure Kubernetes 日志导出到存储帐户或从应用程序洞察中查看旧的 Pod 日志?

javascript - 从 Webpack DLL 构建中排除模块

javascript - 我如何在 React 中通过子索引传递 Prop

javascript - React.js 中每个项目的计数器

C# Azure 设置第二个 ServiceBus 用于故障转移

azure - Azure 存储帐户中的审核事件

c# - WCF 与 ASP.NET Web API

asp.net - 如何将 FormsAuthentication cookie 添加到 HttpClient HttpRequestMessage

c# - 如何在 Asp.net Web API 中使用特定的 CultureInfo

javascript - 如果处理程序在同级组件上调用 setState,则 react 表单 event.preventDefault() 不起作用