WCF服务和添加自定义身份声明

本文关键字:身份 声明 自定义 添加 服务 WCF | 更新日期: 2023-09-27 18:12:56

我创建了一些声明并附加它们线程,然后我想访问操作契约GetCurrentUser();用户邮件声明总是返回null。

问题在哪里?

WCF使用本地IIS,绑定类型为wsHttpBinding。

<serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom"
              customUserNamePasswordValidatorType="SampleService.UserValidator, SampleService" />
</serviceCredentials>

定制验证器;

public class UserValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        if (userName == null || password == null)
        {
            throw new ArgumentNullException();
        }
        if (userName == password)
        {
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, "AbbA"),
                    new Claim(ClaimTypes.Email, "foo@bar.com"),
                    new Claim(ClaimTypes.Role,"Customer")
                };
            var id = new ClaimsIdentity(claims, "Sample");
            var principal = new ClaimsPrincipal(id);
            Thread.CurrentPrincipal = principal;
        }
        else
        {
            throw new FaultException("Wrong Password...");
        }
    }
}

And My OperationContract;

    public string GetCurrentUser()
    {
        var principal = Thread.CurrentPrincipal;
        if (principal.Identity.IsAuthenticated)
        {
            var cp = ClaimsPrincipal.Current;
            var email = cp.FindFirst(ClaimTypes.Email).Value; <<<< It's return always null :(
            return string.Format("Your Email is:{0}", email);
        }
        else
        {
            return "NONE";
        }
    }

WCF服务和添加自定义身份声明

找到解决方案,所以;

我使用WCF表单认证与Wif和会话认证模块(SAM)

你可以找到信息和样本;

http://brockallen.com/2013/01/26/replacing-forms-authentication-with-wifs-session-authentication-module-sam-to-enable-claims-aware-identity/

其他选项启用WCF认证服务;

https://msdn.microsoft.com/library/bb398990

1)https://msdn.microsoft.com/tr-tr/library/bb398862%28v=vs.100%29.aspx

2)

3) https://msdn.microsoft.com/tr-tr/library/bb398778%28v=vs.100%29.aspx