【问题标题】:How to authenticate an access token which is obtained from azure ad b2c through an spa (react app), in a api (asp.net api)?如何在 api(asp.net api)中验证通过 spa(react 应用程序)从 azure ad b2c 获得的访问令牌?
【发布时间】:2022-02-17 19:05:24
【问题描述】:

我有一个 react 应用程序作为我的客户端应用程序和一个 asp.net api 作为我的 api(资源)。我已经设法在我的客户端应用程序中集成了 azure ad b2c 登录。现在我正在准备向我的 api(现在使用 azure ad b2c 保护)发送一个包含访问令牌的请求,以访问我的 api 资源。但我从 api 获得状态码 401,这意味着未经授权。我将访问令牌(承载令牌)从客户端应用程序(react)发送到 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? 我的代码有问题吗?我真的很感谢任何帮助:)

【问题讨论】:

  • 能否请您解码jwt.io 中的令牌并使用获得的变量更新问题。

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


【解决方案1】:

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

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



它看起来如何

注意:删除用于 microsoft graph api 的 user.read 权限。

【讨论】:

  • 我已将端点更改为我的 api 在我的问题中不存在的另一个文件中。但你是对的,我没有在我的 authConfig 文件中包含范围。我已经解决了这个问题,现在身份验证在 api 中工作。非常感谢您的帮助。
  • 我对我的 api 中的 startup.cs 中的身份验证有另一个问题。我怎么能在授权部分扮演角色?我如何在 Azure ad b2c 中创建角色?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2023-01-19
  • 1970-01-01
相关资源
最近更新 更多