简体   繁体   English

如何在Web服务中验证Azure AD Web表单令牌

[英]How to validate Azure AD web form token in web service

I have a WebForms project and a Web Service. 我有一个WebForms项目和一个Web服务。 In web forms i need to authenticate using AzureAD and take Token from this web site. 在Web表单中,我需要使用AzureAD进行身份验证并从此网站获取Token。 This token need to pass to Web Service and web service need to validate this token 此令牌需要传递给Web服务,并且Web服务需要验证此令牌

I got Token from Azure, but validation failing. 我从Azure获得令牌,但是验证失败。 it seems issue with sigingKeys sigingKeys似乎有问题

Default.aspx.cs Page_Load Default.aspx.cs Page_Load

            if (!Request.IsAuthenticated)
            {
                HttpContext.Current.GetOwinContext().Authentication.Challenge(
                   new AuthenticationProperties { RedirectUri = "/" },
                   OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }

On startup.cs 在startup.cs上

 public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                RedirectUri = redirectUri,
                PostLogoutRedirectUri = redirectUri,
                Scope = "openid email profile offline_access " + scopes,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = tenant
                },

                // OpenIdConnect event handlers/callbacks.
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    AuthenticationFailed = OnAuthenticationFailed
                }
            });
        }

        /// <summary>
        /// Handle authorization codes by creating a token cache then requesting and storing an access token
        /// for the user.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            return Task.Run(async () =>
            {
                string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                ConfidentialClientApplication cca = new ConfidentialClientApplication(
                    clientId, redirectUri, new ClientCredential(clientSecret), null, null);
                string[] scopes = this.scopes.Split(new char[] { ' ' });

                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(context.Code, scopes);
                GenUtil.token = result.AccessToken;
                GenUtil.user = result.Account.Username.Split('@')[0];
            });
        }

        /// <summary>
        /// Handle failed authentication requests by redirecting the user to the home page with an error in the query string.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }

On web service validate token 在Web服务上验证令牌

  try
                {
                    ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(metaData, new System.Net.Http.HttpClient());
                    OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
                    string tenant = ConfigurationManager.AppSettings["Tenant"];
                    TokenValidationParameters validationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false,
                        ValidateIssuer = false,
                        IssuerSigningKeys = config.SigningKeys, //.net core calls it "IssuerSigningKeys" and "SigningKeys"
                        ValidateLifetime = false
                    };
                    JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
                    SecurityToken jwt = null;
                    var result = tokendHandler.ValidateToken(GenUtil.token, validationParameters, out jwt);
                    Dictionary<string, object> valueColl = ((JwtSecurityToken)jwt).Payload;
                    if (valueColl["upn"].ToString().Split('@')[0].ToUpper() != GenUtil.user.ToUpper())
                    {
                    }
                }
                catch (Exception ex)
                {

                }

Web form should validate azure authentication and collect token from this. Web表单应验证Azure身份验证并从中收集令牌。 It should pass to Web service and it should validate the token and verify the token. 它应该传递给Web服务,并且应该验证令牌并验证令牌。

If you want to validate access token in your web service, please refer to the following code: On web service validate token 如果要验证Web服务中的访问令牌,请参考以下代码:在Web服务上,验证令牌

public JwtSecurityToken Validate(string token)
        {
            string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";

            ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());

            OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;

            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = false,
                IssuerSigningKeys = config.SigningKeys,
                ValidateLifetime = false
            };

            JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();

            SecurityToken jwt;

            var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);

            return jwt as JwtSecurityToken;
        }

On startup.cs 在startup.cs上

 public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    // Sets the ClientId, authority, RedirectUr,ClientSecret as obtained from web.config
                    ClientId = clientId,
                    ClientSecret = clientSecret,
                    Authority = authority,
                    RedirectUri = redirectUri,
                    // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                    PostLogoutRedirectUri = redirectUri,
                    Scope = OpenIdConnectScope.OpenIdProfile,
                    // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                    ResponseType = OpenIdConnectResponseType.CodeIdToken,
                    // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                    // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                    // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                    TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = false // This is a simplification
                    },
                    // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = OnAuthenticationFailed,
                        AuthorizationCodeReceived = OnAuthorizationCodeReceived
                    }
                }
            ); ;
        }


        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            context.Response.Redirect("/?errormessage=" + context.Exception.Message);
            return Task.FromResult(0);
        }


        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
                .WithRedirectUri(redirectUri)
                .WithClientSecret(clientSecret)
                .Build();

                string[] scopes = { };

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var token = result.AccessToken;
        }

Package.config file : Package.config文件:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net472" />
  <package id="bootstrap" version="3.4.1" targetFramework="net472" />
  <package id="jQuery" version="3.3.1" targetFramework="net472" />
  <package id="jQuery.Validation" version="1.17.0" targetFramework="net472" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net472" />
  <package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net472" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net472" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.7" targetFramework="net472" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net472" />
  <package id="Microsoft.Identity.Client" version="4.3.0" targetFramework="net472" />
  <package id="Microsoft.IdentityModel.JsonWebTokens" version="5.3.0" targetFramework="net472" />
  <package id="Microsoft.IdentityModel.Logging" version="5.3.0" targetFramework="net472" />
  <package id="Microsoft.IdentityModel.Protocols" version="5.3.0" targetFramework="net472" />
  <package id="Microsoft.IdentityModel.Protocols.OpenIdConnect" version="5.3.0" targetFramework="net472" />
  <package id="Microsoft.IdentityModel.Tokens" version="5.3.0" targetFramework="net472" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.11" targetFramework="net472" />
  <package id="Microsoft.Owin" version="4.0.1" targetFramework="net472" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="4.0.1" targetFramework="net472" />
  <package id="Microsoft.Owin.Security" version="4.0.1" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Cookies" version="4.0.1" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.OpenIdConnect" version="4.0.1" targetFramework="net472" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net472" />
  <package id="Modernizr" version="2.8.3" targetFramework="net472" />
  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net472" />
  <package id="Owin" version="1.0" targetFramework="net472" />
  <package id="System.IdentityModel.Tokens.Jwt" version="5.3.0" targetFramework="net472" />
  <package id="WebGrease" version="1.6.0" targetFramework="net472" />
</packages>

For more deatils, please refer to the blog . 有关更多详细信息,请参阅博客

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM