azure - 将 Azure Active Directory 与 .NET Web Api 连接,身份验证始终为 false
问题描述
我正在使用 Angular 7 开发标准 .NET Web Api 2,我需要连接 Azure Active Directory。
我添加了这段代码:
public static void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = configurationManager.AadTenant,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = configurationManager.AadAudience,
},
});
}
我的租户和观众都是正确的。一切正常,令牌有效并且存在于请求中。
问题是 IsAuthenticated 总是错误的,当我在身份中查看声明时,它们是空的
protected override bool IsAuthorized(HttpActionContext actionContext)
{
return base.IsAuthorized(actionContext); // Always false
}
我不知道问题出在哪里。我尝试了很多链接,但没有一个对我有用。有人知道为什么吗?谢谢
解决方案
为了保护您的服务,您可以使用 IsAuthorize 过滤器实现,如下所示:
private static string trustedCallerClientId = ConfigurationManager.AppSettings["ida:TrustedCallerClientId"];
protected override bool IsAuthorized(HttpActionContext actionContext)
{
bool isAuthenticated = false;
try
{
string currentCallerClientId = ClaimsPrincipal.Current.FindFirst("appid").Value;
isAuthenticated = currentCallerClientId == trustedCallerClientId;
}
catch (Exception ex)
{
new CustomLogger().LogError(ex, "Invalid User");
isAuthenticated = false;
}
return isAuthenticated;
}
主体不是取自当前线程,而是取自 actionContext。所以,你必须设置的是动作上下文的请求上下文中的主体:
actionContext.RequestContext.Principal = yourPrincipal;
我假设您的操作 context.requestcontext 没有正确的数据,这就是为什么即使您的请求成功但您的属性始终为假的原因。
参考:
https://www.c-sharpcorner.com/article/azure-active-directory-authentication/
希望能帮助到你。
推荐阅读
- for-loop - for循环中矩阵的特征值
- python - 熊猫数据框索引值作为对象而不是日期时间
- javascript - 如何使用模式和匹配器在java中查找子字符串=“\\r”在字符串=“这是一个\\\\\\rtest \\n\\r字符串”中的出现
- javascript - 如何通过自定义函数使用 Lodash orderby?
- java - 我想知道为什么 FinalizerReference 在我的应用程序中消耗这么多内存
- javascript - React Native:图像未显示在视图中
- selenium-webdriver - Selenium xpath 没有在 chrome 中显示它正在工作的元素
- javascript - Odin 项目 TDD 解决方案
- java - 我的应用程序在真实设备上显示启动画面后崩溃,但在虚拟设备上却没有
- python - 如何在 groupby 中获取第一个值,TypeError:first() 缺少 1 个必需的位置参数:'offset'