【问题标题】:Unable to authenticate web api with Bearer Token无法使用 Bearer Token 对 Web api 进行身份验证
【发布时间】:2016-09-06 22:44:13
【问题描述】:

我目前正在从事一个项目,我有一个 Web API,它使用 Graph API 在我的 Azure AD 中创建帐户并将它们也放入正确的组中。

接下来,我公开了几个 API 调用,它们将被原生 iOS 应用程序和 angularJS Web 应用程序调用。客户编造了一些奇怪的身份验证方式,因为他坚信他的用户是彻头彻尾的白痴。

客户正在将定制好的 iOS 设备交给某些人。该设备具有 Azure AD 用户(主体)和密码。分发它们后,angularJS Web 应用程序上的某些进程会执行此操作,然后该应用程序将调用我的令牌控制器,如下所示:

    public async Task<string> GetTokenForUserAsync(string userPrincipalName, string password)
    {
        var uri = string.Format("{0}/oauth2/token", AuthString);
        using (var httpClient = new HttpClient
        {
            DefaultRequestHeaders = { Accept = { new MediaTypeWithQualityHeaderValue("application/json") } }
        })
        {
            var values = new Dictionary<string, string>
            {
                {"resource", GraphUrl },
                {"client_id", ClientId },
                {"client_secret", ClientSecret },
                {"grant_type", "password" },
                {"username", userPrincipalName },
                {"password", password },
                {"scope", "openid" }
            };

            var content = new FormUrlEncodedContent(values);
            var response = await httpClient.PostAsync(uri, content);

            var responseContent = await response.Content.ReadAsStringAsync();

            return responseContent;
        }

传递的参数不是 100% 准确,而是非常相似:

所以这个调用实际上为我提供了一个 access_token。我遇到的问题是我获得的令牌从未获得授权。我已经尝试了几个启动设置,但都没有工作。

目前我的 Startup.Auth.cs 中有以下代码

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:ClientId"]
            }

        });
        //app.UseWindowsAzureActiveDirectoryBearerAuthentication(
        //    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
        //    {
        //        TokenValidationParameters = new TokenValidationParameters
        //        {
        //            ValidAudience = ConfigurationManager.AppSettings["ida:ClientId"]
        //        },
        //        Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
        //    });
    }

这是我第一次使用 Azure 和 Active Directory。所以我很可能会做一些非常愚蠢的事情。在这个时刻,我不太关心造型和“正确的方式”。我只是想让这个东西工作:,/

希望我正确地描述了我的问题并相应地记录了我的问题。如果您有任何问题,请不要犹豫!

提前致谢

【问题讨论】:

    标签: azure asp.net-web-api2 bearer-token azure-ad-graph-api azure-active-directory


    【解决方案1】:

    我不认为你可以从 var values = new Dictionary 获取访问令牌 { {"资源", GraphUrl }, {"client_id", ClientId }, {"client_secret", ClientSecret }, {"grant_type", "密码" }, {"用户名", userPrincipalName }, {"密码", 密码 }, {“范围”,“openid”} }; 所以你可以尝试其他方法:

           AuthenticationContext aContext =
                    new AuthenticationContext("https://login.microsoftonline.com/tenantid");
                AuthenticationResult aResult =
                    aContext.AcquireToken("https://graph.windows.net",
                                    "1950a258-227b-4e31-a9cf-717495945fc2",
                                    new UserCredential(UserId, PasswordId));
    
                string result = string.Empty;
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", aResult.AccessToken);
                HttpResponseMessage response =
                    httpClient.GetAsync("https://graph.windows.net/tenantid/users/userid?api-version=1.6").Result;
    
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
                Console.WriteLine(result);
                Console.ReadLine();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-09
      • 2017-10-14
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      相关资源
      最近更新 更多