首页 > 解决方案 > 将 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
 }

我不知道问题出在哪里。我尝试了很多链接,但没有一个对我有用。有人知道为什么吗?谢谢

标签: azureauthenticationasp.net-web-apiazure-active-directory

解决方案


为了保护您的服务,您可以使用 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/

希望能帮助到你。


推荐阅读