gpt4 book ai didi

c# - 如何在服务器计算机的 Web API 中验证 WPF 应用程序 Azure token

转载 作者:行者123 更新时间:2023-12-03 02:50:29 25 4
gpt4 key购买 nike

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

                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;

最佳答案

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

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

转到nuget包管理器并浏览System.IdentityModel.Tokens.Jwt将此引用添加到您的项目中。请参阅下面的屏幕截图:

enter image description here

添加以下引用:

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

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

token 验证方法:

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

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

您的 token 验证参数:

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

Note: hook up all the reference and test. for more details you could refer here. If you sill have any query feel free to share. Thanks and happy coding!

关于c# - 如何在服务器计算机的 Web API 中验证 WPF 应用程序 Azure token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56360312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com