邮递员获得有效令牌,但从API获得401 [英] Postman gets a valid token but getting 401 from API
问题描述
我正在尝试使用Postman测试我的ASP.NET Core 2.2 Web API.我的API受Azure AD保护.我一直在使用"Web应用程序API" Microsoft Azure
I am trying to test my ASP.NET Core 2.2 Web API with Postman. My API is protected by Azure AD. I have been using the "Web App your API" Microsoft Azure Sample on GitHub and triple-checked all of the steps.
使用邮递员,我要求它使用OAuth2隐式流程获取令牌,但确实获得了返回的令牌.如果我对令牌进行解码,它似乎包含了我想要的所有声明:aud
,upn
和scp
都有意义.
Using Postman I ask it to get a token using the OAuth2 Implicit flow and I do get a token returned. If I decode the token it seems to contain all the claims I want: aud
, upn
and scp
all make sense.
但是,当我随后使用返回的令牌向API发送请求时,我仍然收到401.
However, when I then send a request to the API using the returned token I still get a 401.
API之所以有效,是因为如果删除[Authorize]
属性,我将获得返回的数据.
The API is working because if I remove the [Authorize]
attribute I get data returned.
如果我尝试通过Web客户端访问API,则会收到错误消息:MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
,但是鉴于令牌中返回了我的upn
,这没有任何意义.
If I try accessing the API with a web client I get an error: MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.
but that makes no sense given that my upn
is returned in the token.
任何人都可以建议采取进一步措施以找出问题所在.
Can anyone recommend further action to figure out what's wrong.
在 TokenAcquisition.cs account
的第381行是null
,因此当随后调用AcquireTokenSilent()
时,结果是null
.
On line 381 of TokenAcquisition.cs account
is null
so when AcquireTokenSilent()
is subsequently called the result is null
.
推荐答案
我放弃了Postman一段时间,并专注于Web客户端.我必须在Azure门户中将Application ID URI
从https://<company>.onmircrosoft.com/<myapi>/user_impersonation
重命名为api://<application_guid>/access_as_user
,并在应用程序代码中也重命名.这使TokenAcquisition.cs开始返回令牌,并且让Web应用程序与API通讯.
I abandoned Postman for a while and focused on a web client. I had to rename my Application ID URI
in the Azure Portal from https://<company>.onmircrosoft.com/<myapi>/user_impersonation
to api://<application_guid>/access_as_user
and similarly in my application code. This made TokenAcquisition.cs start returning a token and I got the Web App talking to the API.
我仍然没有邮递员在工作,尽管现在它返回一条消息:invalid_client
.可能因为我需要使用其他流程.无论如何,我现在很开心.
I still don't have Postman working though now it returns a message: invalid_client
. Probably as I need to use a different flow. Anyhow, I'm happy for the moment.
这篇关于邮递员获得有效令牌,但从API获得401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!