WCF服务和添加自定义Identity声明

时间:2015-09-16 14:35:38

标签: c# .net wcf

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

问题出在哪里?

使用本地IIS和绑定类型的WCF是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...");
        }
    }
}

和我的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";
        }
    }

1 个答案:

答案 0 :(得分:0)