在MVC应用程序中获取访问令牌

时间:2016-07-12 21:07:05

标签: asp.net-mvc oauth-2.0 owin azure-active-directory

我正在尝试检索访问令牌,以便我可以存储它,并在以后将其传递给ExchangeService。 Startup.Auth看起来像这样:

 app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                UseTokenLifetime = false,
                /*
                * Skipping the Home Realm Discovery Page in Azure AD
                * http://www.cloudidentity.com/blog/2014/11/17/skipping-the-home-realm-discovery-page-in-azure-ad/
                */
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = OpenIdConnectNotification.RedirectToIdentityProvider,
                    MessageReceived = OpenIdConnectNotification.MessageReceived,
                    SecurityTokenReceived = OpenIdConnectNotification.SecurityTokenReceived,
                    SecurityTokenValidated = OpenIdConnectNotification.SecurityTokenValidated,
                    AuthorizationCodeReceived = OpenIdConnectNotification.AuthorizationCodeReceived,
                    AuthenticationFailed = OpenIdConnectNotification.AuthenticationFailed
                },

            });

然后在SecurityTokenValidated中我这样做了:

public static async Task<Task>  SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
    {
        string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        var authContext = new AuthenticationContext(aadInstance + "/oauth2/token", false);
        var authResult =await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code,
            new Uri(aadInstance), new ClientAssertion(clientId, "‎5a95f1c6be7bf3c61f6392ec84ddd044acef61d9"));
        var accessToken = authResult.Result.AccessToken;
        context.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", accessToken));
        return Task.FromResult(0);
    }

我没有收到任何错误,但应用程序挂起了这一行:

 var accessToken = authResult.Result.AccessToken;

ClientAssertion是使用我在IIS中安装的SSL证书的指纹构建的,不确定证书是否是错误的类型......

更新: 我更新了SecurityTokenValidated以反映Saca的评论,但我得到了“AADSTS50027:无效的JWT令牌。令牌格式无效”这样的错误。 我也试过这段代码:

   string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            var authContext = new AuthenticationContext(aadInstance, false);
            var cert = new X509Certificate2("...", "...");
            var cacert = new ClientAssertionCertificate(clientId, cert);
            var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(aadInstance), cacert);
            var accessToken = authResult.AccessToken;
            context.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", accessToken));
            return Task.FromResult(0);

但这样我得到“AADSTS70002:验证凭据时出错.AADSTS50012:客户端断言包含无效签名。”

2 个答案:

答案 0 :(得分:3)

应用程序挂起,因为您通过访问authResult的.Result来阻止异步任务的结果。

您应该将其更改为:

public static async Task SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
    string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    var authContext = new AuthenticationContext(aadInstance + "/oauth2/token", false);
    var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code,
        new Uri(aadInstance), new ClientAssertion(clientId, "‎5a95f1c6be7bf3c61f6392ec84ddd044acef61d9"));
    var accessToken = authResult.AccessToken;
    context.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", accessToken));
}

答案 1 :(得分:1)

我成功获得了访问令牌:

 public static async Task<Task> SecurityTokenValidated(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
    {
        string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
        string source = ConfigurationManager.AppSettings["ExchangeOnlineId"];

        var authContext = new AuthenticationContext(aadInstance, false);
        var credentials = new ClientCredential(clientId, clientSecret);
        var appRedirectUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase + "/";
        var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, new Uri(appRedirectUrl), credentials, source);
        var accessToken = authResult.AccessToken;
        var applicationUserIdentity = new ClaimsIdentity(context.OwinContext.Authentication.User.Identity);
        applicationUserIdentity.AddClaim(new Claim("AccessToken", accessToken));
        context.OwinContext.Authentication.User.AddIdentity(applicationUserIdentity);
        return Task.FromResult(0);
    }

最初我想使用ClientAssertion,所以我不必暴露客户端Secret,但管理证书的工作太多......