【问题标题】:401: unauthorized issue in Web API .net core C#401:Web API .net core C# 中的未授权问题
【发布时间】:2021-08-10 12:35:54
【问题描述】:
    I am getting JWT Token from the React UI using AcquireTokenSilent of MSAL. Now, I have to call Graph API using this token in Web API(.net core) in C#.
    Before calling the Graph API I am getting "401 :Unauthorized". Please help me in resolving the issue.       
    
    In Startup.cs I am using following code:
    ----------
    public void ConfigureServices(IServiceCollection services)
                {
                    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                        .AddMicrosoftIdentityWebApi(Configuration,"AzureAd")
                            .EnableTokenAcquisitionToCallDownstreamApi()
                                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                                .AddInMemoryTokenCaches();
                }
        
        
          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
               {
                   app.UseAuthentication();
                   app.UseRouting();
                   app.UseAuthorization();
               }
        
       
         In ProfileController.cs
        
         [HttpPost]
                public async Task<ActionResult> PostProfileItem([FromBody]SetProfile setprofile)
                {
                     
                    HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
                     
                    try
                    {
                        List<HeaderOption> requestHeaders = new List<HeaderOption>() { new HeaderOption("Authorization", "Bearer " + setprofile.access_token) };
                        User profile = await _graphServiceClient.Me.Request(requestHeaders).GetAsync();
                }
               (catch Exception ex)
                {
                }
              return Ok(profile);
            }
        
            SetProfile.cs
        namespace Web.Dto
        {
            public record SetProfile
            {
               [NotMapped]
               [JsonProperty("access_token")]
               [Required]
                public string access_token { get; init; }
               
            }
        
            
        }
    
   
    
    

React UI 代码获取令牌并将访问令牌发布到 ProfileController.cs

if (!graphData && inProgress === InteractionStatus.None) { //表单数据实例 let formData = new FormData() //获取令牌静默 instance.acquireTokenSilent(accessTokenRequest) //then 子句 .then((accessTokenResponse ) => { // 获取令牌静默成功 let accessToken = accessTokenResponse.accessToken; //记录访问令牌 console.log(access token : ${accessToken}) //在API中添加访问令牌的代码 formData.append("access_token", accessToken) / /调用配置文件 API props.userProfileCall(formData) }); //捕获错误的代码 }).catch((error) => { //记录错误 console.log(error); })

【问题讨论】:

  • 最好向我们展示您的 React 部分。你如何传递令牌?
  • 我已经添加了 React 部分。请帮帮我。
  • 几件事需要确认,您的令牌是否需要您尝试呼叫的graph api 的权限?另一件事是您能否check your token here 仔细检查您的上下文是否有效?

标签: c# reactjs azure-active-directory authorization webapi


【解决方案1】:

解决方案 1:

1) 要从 Reactjs 访问任何 Web API 或任何 Ajax 方法 Web API 必须启用 CORS

您需要设置 CORS 政策才能调用 Startup.cs 中的 API。

 services.AddCors(o => o.AddPolicy("default", builder =>
    {
        builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
    })

2) 在您的控制器中,添加 [Authorize] 装饰器,这将确保所有传入请求都有身份验证承载

例子:

 [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
    }

解决方案 2: 确保您授予 User.Read.All 应用程序权限。

  1. 登录Azure portal

  2. 如果您可以访问多个租户,请使用顶部菜单中的 目录 + 订阅 过滤器来选择包含您的客户端应用注册的租户。

  3. 选择 Azure Active Directory > 应用注册,然后选择您的客户端应用程序。

  4. 选择 API 权限 > 添加权限 > Microsoft Graph > 应用程序权限

  1. Microsoft Graph 公开的所有权限都显示在选择权限下。

  1. 选择User.Read.All并点击添加权限

更多详情请参考document

【讨论】:

    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 2020-12-29
    • 2020-02-11
    • 1970-01-01
    • 2021-09-28
    • 2020-03-28
    • 2019-01-04
    • 2017-03-23
    相关资源
    最近更新 更多