gpt4 book ai didi

c# - WCF 用户名身份验证 : Can I get the Username in a custom ServiceAuthorizationManager?

转载 作者:太空狗 更新时间:2023-10-30 00:59:24 25 4
gpt4 key购买 nike

我有一个使用自定义 ServiceAuthorizationManager 的 WCF 服务。自定义身份验证管理器已设置为处理 Windows 和表单例份验证。

但是,如果我连接到设置为 UserName auth 的客户端,我似乎无法在任何地方找到用户名。

客户端代码如下所示:

this.ClientCredentials.UserName.UserName = "user";
this.ClientCredentials.UserName.Password = "pass";
this.Open();
this.MyMethod(); // my actual contract method
this.Close();

然后在服务器上,我有我的自定义授权管理器:

public sealed class AppAuthorizationManager : ServiceAuthorizationManager
{
public override bool CheckAccess(OperationContext operationContext, ref Message message)
{
// would like to check user/pwd here...
}
}

这可能吗?

  • 未设置Thread.CurrentPrincipal
  • operationContext.ServiceSecurityContext.PrimaryIdentity 未设置。
  • operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets 为空。

用户/密码应该在任何地方都可用吗?还是我也必须添加自定义 UsernamePasswordValidator


更新:所以我添加了一个自定义 UserNamePasswordValidator 和一个 IAuthorizationPolicy。我更新的 WCF 配置如下所示:

<behavior name="Server2ServerBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceAuthorization principalPermissionMode="Custom" serviceAuthorizationManagerType="MyApp.AuthManager, MyApp">
<authorizationPolicies>
<add policyType="MyApp.TokenAuthorizationPolicy, MyApp" />
</authorizationPolicies>
</serviceAuthorization>
<serviceCredentials>
<userNameAuthentication customUserNamePasswordValidatorType="MyApp.PFUserNameValidator, MyApp" />
</serviceCredentials>
</behavior>

如果我在所有 3 个类中设置断点,WCF 将抛出异常:

LogonUser failed for the 'username' user. Ensure that the user has a valid Windows account.
at System.IdentityModel.Selectors.WindowsUserNameSecurityTokenAuthenticator.ValidateUserNamePasswordCore(String userName, String password)

在它们运行之前。嗯……

最佳答案

这通常在 UsernamePasswordValidator 中处理- 这是您唯一可以访问密码的地方。但是,这不是您设置委托(delegate)人的地方 - 它应该在 IAuthorizationPolicyEvaluate 方法中,它可能类似于:

bool IAuthorizationPolicy.Evaluate(
EvaluationContext evaluationContext, ref object state)
{
IList<IIdentity> idents;
object identsObject;
if (evaluationContext.Properties.TryGetValue(
"Identities", out identsObject) && (idents =
identsObject as IList<IIdentity>) != null)
{
foreach (IIdentity ident in idents)
{
if (ident.IsAuthenticated &&
ident.AuthenticationType == TrustedAuthType)
{
evaluationContext.Properties["Principal"]
= //TODO our principal
return true;
}
}
}
if (!evaluationContext.Properties.ContainsKey("Principal"))
{
evaluationContext.Properties["Principal"] = //TODO anon
}
return false;
}

(其中 TrustedAuthType 是我们的密码验证器的名称)

有了这个,线程的主体将被设置,我们可以识别自己(并使用基于角色的安全性等)

关于c# - WCF 用户名身份验证 : Can I get the Username in a custom ServiceAuthorizationManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/529485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com