WCF客户端验证默认是Windows,调用时默认将Windows身份传递给服务,执行服务时将身份附加到当前线程

【参考知识点】谁动了我的CurrentPrincipal?解释一下为什么CurrentPrincipal变了,并解决这个问题
https://www.cnblogs.com/Arnu/p/SolvePrincipalFail.html

WCF客户端验证默认是Windows,调用时默认将Windows身份传递给服务,执行服务时将身份附加到当前线程。

比如WCF服务端构造函数中注入IAuthService,在相应实现类AuthService中验证客户端传递过来的Windows身份验证信息(已经附加在Thread.CurrentPrincipal.Identity)
if (Thread.CurrentPrincipal == null || Thread.CurrentPrincipal.Identity == null)
{
throw new AuthenticationException(“无身份验证信息”);
}
IIdentity identity=Thread.CurrentPrincipal.Identity;
if (!identity.IsAuthenticated)
{
throw new AuthenticationException(identity.Name+"(使用的验证类型:"+identity.AuthenticationType+")未经验证!");
}
接着WCF服务端就可以利用该身份验证信息结合数据库的用户及角色权限信息进行相应授权访问了。
客户端程序(以Web程序为例,IIS需要要集成Windows身份验证)获取Windows身份信息可以在Global.asax.cs中PostAuthenticateRequest事件后获取
public override void Init(){
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
PostAuthenticateRequest += PostAuthenticateRequestHandler;
}

private void PostAuthenticateRequestHandler (object sender,EventArgs e)
{
string userName = HttpContext.Current.User.Identity.Name;
…; //再截取“\”后的不带域名的userName
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
……; //用户未经验证的处理
}
}

另外值得了解的是

在SelfServiceHost:ServiceHost中为Description(ServiceDescription类型).Behaviors.Add(包括AuthorizationBehavior:IServiceBehavior)
重点在System.ServiceModel.IService.ApplyDispatchBehavior方法的实现上,过程中拿到OperationContext.Current.ServiceSecurityContext.PrimaryIdentity即客户端传递过来的Windows身份验证信息。

Guess you like

Origin blog.csdn.net/carcarrot/article/details/118331924