c# - 如何在服务器机器的 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;
解决方案
您似乎正在尝试从后端代码验证您的令牌。
获得令牌后,您可以使用System.IdentityModel.Tokens.Jwt
nuget 包来验证您的令牌。要做到这一点
去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
};
}
注意:连接所有参考和测试。有关更多详细信息,您可以参考此处。如果您有任何疑问,请随时分享。感谢和快乐的编码!
推荐阅读
- javascript - 具有相同名称的多个文件未在环回中上传
- javascript - npm run serve 永远挂起 vue
- asp.net - 当我在自定义 GridView 中更新时,TextBox 返回 null
- dns - DNS - 基于地理位置的固定 IP 顺序
- gradle - IntelliJ 2018.3.6 无法识别 gradle 任务和属性
- python - 如何将字符串列表转换为列表列表?
- java - 我应该如何处理 Safari 上的 Selenium .click() 方法?
- jboss - 远程与 jconsole 播种 jboss 7.0 eap 的性能
- android - 使用 Android 的 ConstraintLayout 创建类似表格的视图
- mongodb - 使用 $unwind 和排序的 MongoDB 分页