在WCF中填充PrimaryIdentity

Wil*_*ill 4 .net security wcf

我正在使用简单的HTTP标头将令牌传递给WCF服务进行身份验证(WCF服务需要使用basicHTTPBinding,所以我很遗憾不能使用canned ws-security实现).我想填充PrimaryIdentity对象,以便WCF服务可以检查它以确定经过身份验证的用户.

问题是该OperationContext.Current.ServiceSecurityContext.PrimaryIdentity属性在我尝试填充时是只读的.我已经尝试使用SecurityTokenAuthenticators和IAuthorizationPolicy对象来设置身份信息,但该路由似乎需要使用消息级安全性(例如总是发送用户名和密码),这不是我想要的.

任何人都可以阐明我如何设置PrimaryIdentity字段?

Nab*_*eet 12

您可以创建一个包含IAuthorizationPolicy的类.WCF解析所有标识令牌(X509,WS-Security用户名/传递等),并将它们放在Evaluate函数中的evaluationContext.Properties ["Identities"]中.这将返回一个List给你.如果将此列表替换为包含您自己的实现IIdentity的类的列表,则WCF将读取该列表ServiceSecurityContext.Current.PrimaryIdentity.请确保列表中只包含一个项目,否则您将混淆WCF PrimaryIdentity.Name并将是空字符串.

var myIdentity = new MyIdentity("MyId", otherstuff);
evaluationContext.Properties["Identities"] = new List<IIdentity> {myIdentity};
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望在替换它们之前处理/读取任何标记.

var identities = evaluationContext.Properties.ContainsKey("Identities")
                                 ? (List<IIdentity>) evaluationContext.Properties["Identities"]
                                 : new List<IIdentity>();

var genericIdentity = identities.Find(x => x.AuthenticationType == "MyUserNamePasswordValidator");
Run Code Online (Sandbox Code Playgroud)

genericIdentity.Name - >包含WSS用户名令牌的用户名.

如果您使用WS-Security Username令牌并且不希望任何默认WCF验证,则需要UsernamePasswordValidator(http://msdn.microsoft.com/en-us/library/system.identitymodel.selectors.usernamepasswordvalidator.aspx).因为,我们有一个DataPower设备在消息到达我们的服务之前验证令牌,我们不需要验证用户名和密码.在我们的例子中它只返回true.


mar*_*c_s 5

PrimaryIdentity不是要由您填充的-WCF运行时的工作是确定谁在呼叫并进行PrimaryIdentity相应的设置。

因此,如果您使用Windows凭据进行呼叫,那么您将在此WindowsIdentity存储一个文件。如果您使用的是ASP.NET成员资格提供程序,则会将该调用方存储在中PrimaryIdentity

实际设置此设置的唯一方法是创建自己的自定义服务器端身份验证机制,并将其插入WCF。

看到: