.NET 4.6.1 API中Windows与Ping多身份认证共存的实现问题求助
.NET 4.6.1 API中Windows与Ping多身份认证共存的实现问题求助
大家好,我最近在做.NET 4.6.1的API项目,需要实现Windows身份认证和Ping身份认证共存的多认证逻辑,目前卡在了一个问题上,想请教下各位前辈。
我现在的情况是这样的:
- 我写了一个继承自
AuthorizeAttribute的自定义认证过滤器CustomAuthFilter,逻辑是先尝试用Windows身份认证,失败的话再走Ping认证 - 控制器方法上同时标记了
[Authorize]和[CustomAuthFilter],但两种认证没法正常兼容:- 去掉
[Authorize]只留自定义过滤器时,Ping认证能正常工作,但Windows认证会失败——因为HttpContext.Current.User.Identity.Name返回的是空字符串,根本没法匹配配置文件里的允许用户列表 - 保留
[Authorize]的话,Windows认证能正常通过,但Ping认证又完全触发不了了
- 去掉
先贴下我的代码:
控制器代码
public class TestController { [Authorize] [CustomAuthFilter] public async Task<IHttpActionResult> Get() { return <some object>; } }
自定义认证过滤器代码
public class CustomAuthFilter:AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext actionContext) { var user = HttpContext.Current.User.Identity.Name; // 这里返回空字符串 var isAuthorised = AuthenticateWindows(user); // 如果Windows认证失败,再尝试Ping认证,后续逻辑写在这里 return isAuthorised; } protected bool AuthenticateWindows(string user) { var usersList = ConfigurationManager.AppSettings["AllowedUsers"].Split(',').ToList(); if (!usersList.Select(x => x.ToUpper()).ToList().Contains(user.ToUpper())) return false; return true; } }
我自己排查下来,感觉问题应该是当只使用自定义过滤器时,Windows认证的身份信息没有被正确填充到HttpContext里,但不知道该怎么调整才能让两种认证方式都能被正确触发:
- 有没有办法让Windows认证先完成身份信息的填充,再进入自定义过滤器的逻辑?
- 或者我的过滤器逻辑写得有问题,应该怎么修改才能同时兼容两种认证的触发条件?
- 有没有项目配置上的遗漏,比如Web.config里需要加什么特殊配置才能支持两种认证共存?
麻烦各位大佬帮忙看看,感谢感谢!
相关产品推荐
相关产品推荐

