是這樣的嗎?
public sealed class CustomSecurityAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["X-SessionId"]) && IsAuthenticated(ilterContext.HttpContext.Request.Headers["X-SessionId"]))
filterContext.Result = new HttpNotFoundResult();
}
private bool IsAuthenticated(string sessionId)
{
// get your user details from your database (or whatever)
var user = new UserRepository().Get(sessionId);
if (user == null)
return false;
// build up an identity, use your own or out of the box.
FormsIdentity itentity = new MyIdentity(user);
// Set the user
filterContext.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(itentity , user.Roles);
return true;
}
}
你將不得不當前會話存儲在數據庫中,因此,例如,當在搶用戶登錄的會話ID,並把它貼在數據庫中,這樣你就知道他們1..1當前會話。
然後,您可以查看它作爲您的身份驗證的一部分。
編輯:
讓我們退後一步,從不考慮一下cookie和session。
你有一個網站和一個寧靜的API,他們都服務於不同的目的和客戶,並有不同的安全要求。
那麼保護你的Api最常用的選項是什麼?
我會建議使用這些常見的場景,以確保您不會錯過的東西,打開你的自我可達安全漏洞。
有沒有理由不能使用這些?
這是一個罰款開始的過濾器,但是我如何告訴asp.net使用X-SessionId查找(現有)會話並關聯HttpContext.Current.User和所有其他變量? –
我已經爲潛在解決方案更新了我的答案,說實話,你有點前往野外,可能有更好的方法,像解決方案上的單一標誌可能是betteR? – shenku
解決安全問題(將會話存儲在數據庫中)。我認爲ASP.NET將所有會話存儲在內部數據存儲中(可能只是一張地圖)。是否可以引用它,這樣我可以像普通客戶那樣將其他內容放入Session中? –