【问题标题】:Azure AD - Using Graph API access token from Angular SPA in C# Web APIAzure AD - 在 C# Web API 中使用来自 Angular SPA 的 Graph API 访问令牌
【发布时间】:2021-09-27 09:32:45
【问题描述】:

在 Azure AD 企业应用程序方面,我似乎遗漏了一些基本的东西。
我有一个作为 Angular SPA 运行的应用程序,其后端 ASPNETCore API 在 Azure AD 中有 2 个单独的应用程序注册。 MyAPI 在 MySPA 中作为范围“access_as_user”公开。
MyAPI 没有自己的身份验证流程。

我想通过 MyAPI 实现委托访问 MS Graph API 调用。目前它仅作为具有应用程序权限的守护程序服务运行。

MySPA 可以毫无问题地调用https://graph.microsoft.com/v1.0/me/,并返回个人资料。
我可以看到 jwt 具有 User.Read 范围:

"scp": "openid profile User.Read email"

MyAPI 使相同的请求失败,并出现以下错误:

code: "InvalidAuthenticationToken"
message: "Access token validation failure. Invalid audience."
public async Task<IActionResult> GetProfile([FromHeader] string authorization)
{
   var tokenFromHeader = authorization.Replace("Bearer ", "");
   return await ("https://graph.microsoft.com/v1.0/me/")
      .WithOAuthBearerToken(tokenFromHeader)
      .WithHeader("Content-Type", "application/json")
      .GetJsonAsync();
    }

JWT 自然有 scoped 权限,所以观众错误是有道理的

"aud": "api://XXXXXXXXXXXXXXXXXXXXXXXX",
"scp": "access_as_user"

MyAPI 如何代表用户访问 MS Graph API?

【问题讨论】:

    标签: c# asp.net-core microsoft-graph-api msal msal-angular


    【解决方案1】:

    设法使用 Graph SDK 解决了这个问题

    我在.AddMicrosoftIdentityWebApi(Configuration)之后的启动中添加了以下内容

    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddMicrosoftGraph()
    .AddInMemoryTokenCaches();
    

    这让我可以在我的 API 控制器中注入服务客户端:

    public GraphAPIController(GraphServiceClient client)
    {
       this.client = client;
    }
    
    public async Task<IActionResult> GetProfile()
    {
       return await client.Me.Request().GetAsync();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-31
      • 2022-01-06
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多