2015-12-21 59 views
3

我正在使用Angularjs和Asp.net Web API的UI應用程序。對於實時更新,我使用SignalR。 Web API和SignalR由不同的進程託管。 Web API將認證用戶並返回令牌。我將查詢字符串中的相同標記發送給SignalR進行授權。授權代碼成功運行,但Context.User在OnConnected方法內爲null,但在註冊中心方法中,主體已正確設置。OnConnected上的SignalR Context.User爲空

請找到下面的代碼。預先感謝您的幫助。

[TokenAuthorize] 
public class MyHub : Hub 
{ 
    public void Register(string token) 
    { 
     // Context.User is set to the appropiate principal 
    } 

    public override Task OnConnected() 
    { 
     //Context user is set to null 
    return base.OnConnected(); 
    } 

    public override Task OnDisconnected(bool stopCalled) 
    { 
     return base.OnDisconnected(stopCalled); 

    } 
} 

public class TokenAuthorizeAttribute : AuthorizeAttribute 
{ 

    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) 
    { 
     var tokenId = request.QueryString.Get("Token"); 
     try 
     { 
      var principal = TokeService.ValidateToken(tokenId); 
      if (principal != null) 
      { 
       Thread.CurrentPrincipal = principal; 
       request.Environment["server.User"] = principal; 

       return true; 
      } 
     } 
     catch (Exception) 
     { 
      return false; 
     }   

     return false; 

    } 

    public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, 
     bool appliesToMethod) 
    { 
     var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId; 
     var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment; 
     var principal = environment["server.User"] as ClaimsPrincipal; 
     if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated) 
     { 
      hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), 
       connectionId); 
      return true; 
     } 
     return false; 
    } 


    protected override bool UserAuthorized(System.Security.Principal.IPrincipal user) 
    { 
     if (user == null) 
     { 
      throw new ArgumentNullException("user"); 
     } 

     var principal = user as ClaimsPrincipal; 

     if (principal != null) 
     { 
      Claim authenticated = principal.FindFirst(ClaimTypes.Authentication); 
      if (authenticated != null && authenticated.Value == "true") 
      { 
       return true; 
      } 
      else 
      { 
       return false; 
      } 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 
+0

爲什麼你不使用singalr作爲消息發送它? – cpoDesign

回答

0

它有可能是與其中signalr配置身份驗證配置和Web API配置的調用順序。您必須在配置web api之前調用mapsignalr。不幸的是,我不知道如何在mapsignalr函數之前調用web api的配置。因爲我的web api配置是從global.asax觸發的GlobalConfiguration.Configure(WebApiConfig.Register);

相關問題