简体   繁体   English

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

[英]Get access token in MVC application

I am trying to retrieve the access token so I can store it, and pass it to an ExchangeService later on. 我正在尝试检索访问令牌,以便可以存储它,并在以后将其传递给ExchangeService。 Startup.Auth looks like this: 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
                },

            });

then in SecurityTokenValidated I did this: 然后在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);
    }

I don't get any errors but the application hangs on this line: 我没有收到任何错误,但是应用程序挂在这行上:

 var accessToken = authResult.Result.AccessToken;

The ClientAssertion was constructed using a thumbprint of a SSL certificate that I have installed in IIS, not sure if the certificate is the wrong type... ClientAssertion是使用我已在IIS中安装的SSL证书的指纹构造的,不确定该证书的类型是否正确...

UPDATE: I updated the SecurityTokenValidated to reflect Saca's comment but I get an "AADSTS50027: Invalid JWT token. Token format not valid" error this way. 更新:我更新了SecurityTokenValidated以反映Saca的评论,但是我收到“ AADSTS50027:无效的JWT令牌。令牌格式无效”这样的错误。 I also tried this code: 我也尝试了这段代码:

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

but this way I get "AADSTS70002: Error validating credentials. AADSTS50012: Client assertion contains an invalid signature." 但是这样我得到“ AADSTS70002:验证凭据出错。AADSTS50012:客户端断言包含无效签名。”

The application hangs because your blocking on the result of an async taskby accessing the .Result of authResult. 应用程序挂起,因为您通过访问authResult的.Result阻止了异步任务的结果。

You should change that to: 您应该将其更改为:

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

I managed to get the access token tike this: 我设法获得了访问令牌:

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

Initially I wanted to use a ClientAssertion so I don't have to expose the client Secret but it's too much work managing the certificate... 最初,我想使用ClientAssertion,因此不必公开客户端的Secret,但是管理证书的工作太多了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从一个 MVC5 应用程序获取访问令牌到另一个 MVC5 应用程序 - How to get access token from one MVC5 application to another MVC5 application 如何在MVC应用程序上访问ACS令牌? - How to access the ACS token on mvc application? 从MVC应用程序中的ClaimsPrincipal获取bootStrapContext标记 - Get bootStrapContext token from ClaimsPrincipal in MVC application Azure Active Directory - 存储访问令牌的MVC应用程序最佳实践 - Azure Active Directory - MVC application best practices to store the access token 在 MVC 客户端(IdentityServer)中自动获取 access_token - Automatically get access_token in MVC client (IdentityServer) 使用Asp.Net MVc获取Google文档api刷新令牌和访问令牌 - Get the google docs api refresh token and access token using Asp.Net MVc 处理OAuth 2.0身份验证 - 在ASP.NET MVC应用程序中获取令牌重定向令牌响应 - Handle OAuth 2.0 Authentication - Get token redirect token response in ASP.NET MVC application MVC访问应用程序设置 - MVC access application settings 我应该将来自OAuth2的访问令牌存储在MVC应用程序中的什么位置? - Where should I store the access token from OAuth2 in a MVC application? 如何使用ASP.NET MVC的Windows集成登录从Azure AD获取访问令牌? - How to get access token from Azure AD using Windows Integrated login from ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM