【发布时间】: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