【问题标题】:401 Calling Authorized WebApi Endpoint401调用授权的WebApi端点
【发布时间】:2017-03-17 09:03:18
【问题描述】:

我有一个 Angular 2 应用程序,我正在针对 Azure AD 进行身份验证,然后调用已开发的 WebApi 以获取更多信息。

我首先将窗口位置更改为 SSO 的 Azure 登录页面

window.location.href =  "https://login.microsoftonline.com/" + 
        this.tenantId + 
        "/oauth2/authorize?" +
        "response_type=id_token+token&" +
        "response_mode=fragment&" +
        "client_id=" + this.clientId + "&" +
        "redirect_uri=" + encodeURIComponent(window.location.href) + "/&" +
        "scope=openid&" +
        "state=" + this.state + "&" +
        "nonce=" + this.nonce;

然后我从哈希中获取 access_token 参数并将其传递给调用我的 Api 的服务

从 Angular 2 调用 WebApi

    public testApi(token): Observable<any> {
    let headers = new Headers({
        'Authorization': 'Bearer ' + token, 'Accept': 'application/json; odata.metadata=minimal' });
    let options = new RequestOptions({ headers: headers });
    return this.httpService.get('/api/values', options)
        .map((response: Response) => response.json());
}

此呼叫返回带有此消息的 401

Bearer error="invalid_token", error_description="签名无效"

环顾四周,我认为这可能与我在 Api 端设置 OWIN 的方式有关,但在阅读了 MSFT 文档后,应该是这样的

在 Statup.cs 中配置部分

   app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
            Audience = Configuration["Authentication:AzureAd:Audience"]
        });

appsettings.json

  "Authentication": {
     "AzureAd": {
       "AADInstance": "https://login.microsoftonline.com/",
       "Audience": "https://isaaclevin.com/testlogin",
       "ClientId": "26931518-d4e2-4ad7-bc78-64857754bbf3",
       "Domain": "isaaclevin.com",
       "TenantId": "3335f25c-177f-424d-96cc-5a5a3d1798cd"
    }

最后是带有授权属性的简单 API

    [Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

不太确定我在这里做错了什么,但这肯定是一个身份验证问题。如果我关闭 [Authorize] 属性,则 api 调用有效(但这很明显)。我正在客户端验证令牌,它工作得很好。

【问题讨论】:

  • 在您重试获取新的访问令牌以再次调用您的 Web API 后,您能否重现此问题?为了缩小这个问题的范围,我还建议您使用 fiddler 捕获 access token,并且您可以使用来自here 的代码验证该令牌。

标签: angular asp.net-web-api owin azure-active-directory


【解决方案1】:

为了解决这个问题,我必须将资源添加到登录调用中。我现在遇到了持续请求.consent 的问题,但我可以很好地处理 api

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2013-12-07
  • 2022-11-08
相关资源
最近更新 更多