自定义标识,身份主体

在windows程序的身份验证中,如果不是用windows集成验证,那么我们通常会使用GenericIdentity,和GenericPrinciple这两个类来做。

但是他们有些问题

例如GenericIdentity是不保存密码的,这当我们需要在后续的操作中使用当前用户的一些身份去做就可能会很麻烦,例如登录之后,我们以后调用的web service的每个方法都要求身份验证的情况。

例如GenericPrinciple是不保存角色列表的。这可能也会有些麻烦的。为此,我自己写了两个类型来改善这些问题

1. 导入的空间

using System.Collections.Generic;
using System.Text;

using System.Threading;
using System.Security.Principal;

2. 自定义标识

public class MyIdentity : IIdentity {

    #region IIdentity 成员

    public string AuthenticationType
    {
        get { return "My Custom AuthenticationType"; }
    }

    public bool IsAuthenticated
    {
        get {
            return true;
        }
    }

    public string Name
    {
        get {
            return _userName;
        }
    }

    private string _userName;
    private string _password;
    public MyIdentity(string userName)
    {
        _userName = userName;
    }

    public MyIdentity(string userName, string password)
    {
        _userName = userName;
        _password = password;
    }

    public string Password
    {
        get {
            return _password;
        }
    }
    #endregion
}

3. 自定义身份主体

public class MyPrinciple : IPrincipal {

    #region IPrincipal 成员

    public IIdentity Identity
    {
        get { return _identity; }
    }

    public bool IsInRole(string role)
    {
        return Roles.Contains(role);  
    }

    public MyPrinciple(MyIdentity identity, string[] roles) {
        _identity = identity;
        _roles = roles;
    }
    private MyIdentity _identity;
    private string[] _roles;

    public MyList<string> Roles {
        get {
            MyList<string> result = new MyList<string>();
            if (_roles != null)
            {
                result.AddRange(_roles);
            }
            return result;
        }
    }

    public override string ToString()
    {
        return string.Format("用户名为:{0},拥有的角色为:{1}",_identity.Name,Roles.ToString());
    }
    #endregion
}

4. 作为辅助,我专门定义了一个泛型的列表类,这样就可以直接把列表输出为字符串了

public class MyList<T> : List<T>
{
    public override string ToString()
    {
        return ToString(",");//默认用逗号分隔
    }

    public string ToString(string splitChar) //用户可以定义分割字符
    {
        StringBuilder sb = new StringBuilder();
        foreach (T t in this)
        {
            sb.AppendFormat("{0}{1}", t, splitChar);
        }

        string result = sb.ToString();
        if (result.LastIndexOf(splitChar) == result.Length-1)
            return result.Substring(0, result.Length - 1);
        else
            return result;
    }
}

 

5. 具体的使用

MyIdentity identity = new MyIdentity("chenxizhang", "password");
MyPrinciple principle = new MyPrinciple(identity, new string[] { "Admin" });
Thread.CurrentPrincipal = principle;

原文地址:https://www.cnblogs.com/chenxizhang/p/1269658.html