将承载令牌写入Javascript

时间:2015-09-08 19:04:21

标签: oauth-2.0 azure-active-directory openid-connect bearer-token

我正在尝试做一个概念验证。我正在使用Azure Active Directory并尝试在旧项目中实施OAuth。

这个项目的一半是使用Web Forms,另一半是通过javascript直接在另一个项目中调用WebAPI。

作为测试,我通过UseOpenIdConnectAuthentication的AuthorizationCodeReceived通知事件获取Bearer Token。我使用以下代码快速将令牌写入调用WebAPI的页面:

 $.ajax({
                        url: baseVotingHeaderURL,
                        type: 'GET',
                        dataType: "json",
                        beforeSend: function(xhr){
                            xhr.setRequestHeader('Authorization', 'Bearer ' + XXXXXXXXXXXXXXXXX);
                        },
                        success: function(result) {
                            options.success(result);
                        },
                        error: function(err) {
                            options.error(err);
                        }
                    });

我可以在Fiddler中看到令牌被传递:

没有代理授权标头。 授权标题存在:Bearer XXXXXXXXXXXXXXXX(我显然用X代替了令牌)

我仍然收到未经授权的401。

为什么这不起作用?

以下是Startup.Auth.cs

中的代码
app.SetDefaultSignInAsAuthenticationType( CookieAuthenticationDefaults.AuthenticationType );
app.UseCookieAuthentication( new CookieAuthenticationOptions( ) );

app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
    Tenant = "XXXXXX.onmicrosoft.com",
    AuthenticationType = "OAuth2Bearer",
    TokenValidationParameters = new TokenValidationParameters( )
    {
        ValidAudience = "https://XXXX.onmicrosoft.com/XXXXX"
    }
} );

app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
            Authority = "https://login.microsoftonline.com/XXXXX.onmicrosoft.com",
            PostLogoutRedirectUri = "https://XXXXXXX/gbl/Home.aspx",
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse( );
                    context.Response.Redirect( "/Error?message=" + context.Exception.Message );
                    return Task.FromResult( 0 );
                },              
                AuthorizationCodeReceived = context =>
                {
                    var client = ClientId;
                    var key = "XXXXXXXXXXXXXXXXXXX=";                               

                    var credential = new ClientCredential( client, key );
                    var authority = String.Format( CultureInfo.InvariantCulture, @"https://login.microsoftonline.com/{0}", "XXXXX.onmicrosoft.com" );
                    var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext( authority );

                    Uri redirectUri = new Uri( HttpContext.Current.Request.Url.GetLeftPart( UriPartial.Path ) );
                    var apiResourceId = "https://graph.windows.net";
                    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            context.Code, redirectUri, credential, apiResourceId );

                    EndpointAndTokenHelper.DecodeAndWrite( result.AccessToken );
                    System.Diagnostics.Debug.WriteLine( result.AccessToken );

                    return Task.FromResult( 0 );
                }
            }
        } );
}

1 个答案:

答案 0 :(得分:0)

我是逐字跟随这些例子的。但是,authContext.AquireTokenByAuthorizationCode中的最后一个参数应该是我的WebAPI资源,而不是https://graph.windows.net

我不知道为什么示例使用https://graph.windows.net