授权模块代码片段:
/// <summary>
/// HTTP模块默认授权配置
/// </summary>
public class Authorization
{
Dictionary<string, string> users;
bool hasValidate;
/// <summary>
/// 获取用户总数
/// </summary>
public int UserCount
{
get
{
return this.users.Count;
}
}
/// <summary>
/// 是否具有验证项
/// </summary>
public bool HasValidate
{
get { return this.hasValidate; }
}
internal Authorization()
{
this.users = new Dictionary<string, string>();
this.LoadUsers("Authorization");
this.hasValidate = this.users.Count > 0;
}
/// <summary>
/// Authorization
/// </summary>
/// <param name="sectionName">配置节名称</param>
public Authorization(string sectionName)
{
if ("Authorization".Equals(sectionName, StringComparison.OrdinalIgnoreCase))
throw new ArgumentOutOfRangeException("sectionName", "no allows you to define Authorization");
this.users = new Dictionary<string, string>();
this.LoadUsers(sectionName);
this.hasValidate = this.users.Count > 0;
}
private void LoadUsers(string sectionName)
{
var section = System.Configuration.ConfigurationManager.GetSection(sectionName) as IDictionary;
if (section != null)
{
var enumerator = section.GetEnumerator();
while (enumerator.MoveNext())
{
this.users.Add(Convert.ToString(enumerator.Key), Convert.ToString(enumerator.Value));
}
}
}
/// <summary>
/// 检验是否合法
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns>true 通过 / false 不通过</returns>
public bool Validate(string username, string password)
{
if (this.hasValidate == false)
{
//不需要认证
return true;
}
var sourcePassword = "";
return this.users.TryGetValue(username, out sourcePassword) && sourcePassword.Equals(password);
}