无法使用Bearer Token验证web api

时间:2016-05-11 13:29:38

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

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

接下来我暴露了几个API调用,这些调用将由本机iOS应用程序以及angularJS Web应用程序调用。客户已经编造了一些奇怪的认证方式,因为他坚信他的用户是完全蠢货。

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

    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。所以我很可能做一些非常愚蠢的事情。在这个时刻,我并不关心造型和“正确的方式”。我只想让这件事起作用:/ /

希望我正确地描述了我的问题并相应地记录了我的问题。如果您有任何疑问,请随时询问!

提前感谢一堆

1 个答案:

答案 0 :(得分:0)

我认为你不能从var values = new Dictionary获得accessstoken             {                 {&#34; resource&#34;,GraphUrl},                 {&#34; client_id&#34;,ClientId},                 {&#34; client_secret&#34;,ClientSecret},                 {&#34; grant_type&#34;,&#34;密码&#34; },                 {&#34;用户名&#34;,userPrincipalName},                 {&#34;密码&#34;,密码},                 {&#34;范围&#34;,&#34; openid&#34; }             }; 所以你可以尝试其他方法:

       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();