我使用this教程通过基本身份验证保护我的Web-API调用。基本上它会检查请求上是否有auth标头,然后针对数据库证明此标头:
public static bool CheckPassword(string user, string password)
{
//Do a Database checkup
if(CheckDB(user,password)) {
//if true, set the principal
var identity = new GenericIdentity(user);
SetPrincipal(new GenericPrincipal(identity,null));
}
else {
//return 401...
}
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
这很好用。但它会查询数据库中的每个请求。即使我只是请求一个JavaScript文件。
我想优化此过程,只需在第一个请求中调用CheckDB()
即可。以下所有请求都不需要其他数据库请求。是否可以保存校长?我尝试检查Thread.CurrentPrincipal
,但它接缝重新初始化每个请求。
答案 0 :(得分:1)
您有几个选择:
使用这些方法中的任何一种" CheckPassword"方法会将密码与缓存中的密码进行比较,或者检查cookie,如果结果令人满意,则直接创建新的主体而不调用数据库。