首页 > 解决方案 > 如何在服务器机器的 Web API 中验证 WPF 应用程序 Azure 令牌

问题描述

我有一个 WPF 应用程序,它将通过 Azure AD 进行身份验证并返回一个令牌。在调用方法 Web API 时,我们将此令牌传递给服务器机器。在服务器中,我们需要验证令牌是否有效。你能帮我获取服务器机器中的验证码吗

                string aadInstance = service.SelectSingleNode("AADInstance").InnerText;
                string tenant = service.SelectSingleNode("Tenant").InnerText;
                string clientId = service.SelectSingleNode("ClientId").InnerText;
                string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
                authContext = new AuthenticationContext(authority, new FileCache());
                Uri redirectUri = new Uri(service.SelectSingleNode("RedirectUri").InnerText);
                string resourceId = service.SelectSingleNode("ResourceId").InnerText;
                AuthenticationResult result = null;
             try
            {
                result = await authContext.AcquireTokenSilentAsync(resourceId, clientId);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    result = await authContext.AcquireTokenAsync(resourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
                }
            }
            tocken = result.AccessToken;

标签: c#azureazure-active-directory

解决方案


您似乎正在尝试从后端代码验证您的令牌。

获得令牌后,您可以使用System.IdentityModel.Tokens.Jwtnuget 包来验证您的令牌。要做到这一点

nuget package manager浏览以System.IdentityModel.Tokens.Jwt将此引用添加到您的项目。请看下面的屏幕截图:

在此处输入图像描述

添加以下参考:

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

设置包后,设置以下代码:

令牌验证方法:

private  bool ValidateToken(string yourToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            IPrincipal principal = tokenHandler.ValidateToken(yourToken, validationParameters, out validatedToken);
            return true;
        }

您的令牌验证参数:

static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

private static TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateLifetime = false, // Because there is no expiration in the generated token
                ValidateAudience = false, // Because there is no audiance in the generated token
                ValidateIssuer = false,   // Because there is no issuer in the generated token
                ValidIssuer = "Sample",
                ValidAudience = "Sample",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token
            };
        }

注意:连接所有参考和测试。有关更多详细信息,您可以参考此处。如果您有任何疑问,请随时分享。感谢和快乐的编码!


推荐阅读