您认为这种身份验证方法存在任何安全问题或有任何建议吗?
WebAPI是基于REST的.用户通过调用身份验证控制器( Authentication )登录,如果未经过身份验证,则期望401或在头中有一个会话令牌的200。
Session session = null;
try
{
session = Models.User.Login(user);
}
catch (Exception ex)
{
var errResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
{
Content = new StringContent("Invalid Username or Password"),
ReasonPhrase = ex.InnerException.ToString()
};
throw new HttpResponseException(errResponse);
}在除身份验证之外的每一次呼叫中,请求都会被截获,并期望有一个会话头。如果数据库中存在会话,则对请求进行身份验证。
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
//Unauthorized
if (HttpContext.Current.Request.Headers[SessionHeader] == null)
{
var errResponse = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
Content = new StringContent(SessionError),
ReasonPhrase = SessionError
};
return errResponse;
}
string sessionHeader = HttpContext.Current.Request.Headers[SessionHeader];
Session session = Session.Lookup(sessionHeader);
if (session == null)
{
throw new SecurityException("No session record exists");
}
else if (session.Expired)
{
throw new SecurityException("Session Expired");
}
else
{
session.LastAccess = DateTime.Now;
session.Save();
var identity = new SecurityPrincipal(session);
Thread.CurrentPrincipal = identity;
HttpContext.Current.User = identity;
}会话查找是使用实体框架完成的
public static Session Lookup(string sessionId) {
using (var context = new SingleAppContextCustom())
{
var session = (from s in context.Sessions.IncludeChildren()
where s.SessionId == sessionId
select s).FirstOrDefault();
return session;
}
}发布于 2016-08-02 19:17:37
通常,您希望尽可能少地提供为什么拒绝访问的信息。因此,我会将这一节代码修改为:
if (session == null || session.Expired)
{
throw new SecurityException("Access Denied");
}据推测,此异常将转换为适当的HTTP状态代码。
SendAsyc是一个执行安全性的函数的奇怪名称,但是您可能有这样做的原因。尽管如此,似乎缺少了一些东西,因为我不知道它在哪里,或者返回一个Task。
https://codereview.stackexchange.com/questions/128392
复制相似问题