我正在開發一個應用程序,它使用HttpModule來執行自定義驗證和授權。我的問題是在SignalR上下文對象中無法訪問在HttpModule中設置的用戶標識。是否可以使用HttpModule來驗證SignalR
我做了以下我的HttpModule後自定義驗證邏輯的BeginRequest處理程序:
var userClaims = new List<Claim>();
userClaims.Add(new Claim(ClaimTypes.NameIdentifier, <some id>));
userClaims.Add(new Claim(ClaimTypes.Name, <some name>));
userClaims.Add(new Claim(ClaimTypes.Email, <da email>));
userClaims.Add(new Claim(ClaimTypes.Authentication, "true"));
var id = new ClaimsIdentity(userClaims);
var principal = new ClaimsPrincipal(new[] { id });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
我認爲這絕對會做一切以下行爲就像請求被驗證,但是這種情況並非如此。
我創建了一個SignalR AuthorizeAttribute類來處理,看起來像這樣的認證:
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class CustomAuthAttribute : AuthorizeAttribute
{
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request)
{
if (HttpContext.Current.Request.Path.StartsWith("/signalr/connect"))
{
var test = (ClaimsPrincipal)HttpContext.Current.User;
var test2 = (ClaimsPrincipal)Thread.Current.Principal;
}
return true;
}
public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubContext, bool appliesToMethod)
{
var test = (ClaimsPrincipal)hubContext.Hub.Context.User;
return true;
}
}
所以我的計劃是從AuthorizeHubMethodInvocation方法中訪問hubContext.Hub.Context.User VAR做任何我需要自定義授權。但是,它只包含默認的WindowsPrincipal。
如果我查看AuthorizeHubConnection調用(實際上它是一個常規的HTTP請求而不是websocket調用),我看到HttpContext.Current對象也沒有用戶設置,因爲它應該。
我確實看到我可以訪問HttpContext.Current.Items集合。我猜想我可以用這個將信號從模塊拋到SignalR上下文中,但我不確定這是我應該做的。
最好是簡單地將HttpModule重寫爲OWIN中間件?無論如何,如果我們更新到ASP.NET 5,看起來我不得不改變東西;沒有什麼比MS產品更能爲您提供工作保障。