2017-01-06 59 views
4

我試圖在後端應用程序(天青移動應用程序)中構建通知機制。 我設法覆蓋了授權屬性,以使通知集線器僅可供授權用戶訪問。使用AppServiceAuthentication和signalR

public class QueryStringBearerAuthorizeAttribute : Microsoft.AspNet.SignalR.AuthorizeAttribute 
{ 
    public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) 
    { 

     try 
     { 
      var user = (request.Environment["server.User"] as ClaimsPrincipal).FindFirst(ClaimTypes.NameIdentifier).Value; 
      if (user == null) 
       return false; 
      return true; 

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

    public override bool AuthorizeHubMethodInvocation(IHubIncomingInvokerContext hubIncomingInvokerContext, bool appliesToMethod) 
    { 
     var connectionId = hubIncomingInvokerContext.Hub.Context.ConnectionId; 
     // check the authenticated user principal from environment 
     var environment = hubIncomingInvokerContext.Hub.Context.Request.Environment; 
     var principal = environment["server.User"] as ClaimsPrincipal; 
     if (principal != null && principal.Identity != null && principal.Identity.IsAuthenticated) 
     { 
      // create a new HubCallerContext instance with the principal generated from token 
      // and replace the current context so that in hubs we can retrieve current user identity 
      hubIncomingInvokerContext.Hub.Context = new HubCallerContext(new ServerRequest(environment), connectionId); 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 

在startup.cs文件:

var authorizer = new Hubs.QueryStringBearerAuthorizeAttribute(); 

var module = new AuthorizeModule(authorizer, authorizer); 
GlobalHost.HubPipeline.AddModule(module); 
app.MapSignalR(); 

從控制檯應用程序(C#),我能夠通過提供在X的Zumo-AUTH頭連接到所述通知轂。但是,從Web應用程序中,無法設置標題。

有沒有辦法使用查詢字符串來檢查身份驗證令牌而不是頭?

+0

你是什麼意思與Web應用程序的XHR頭?瀏覽器網站? – DomeTune

+0

是的,我的意思是一個網站 – Kira

+0

你使用XHR或[獲取](https://github.com/github/fetch) – DomeTune

回答

-1

要添加,您可以使用

var url = "www.example-mobile-azure-app.com"; 
var xhr = new XMLHttpRequest(); 
xhr.setRequestHeader('X-ZUMO-APPLICATION', 'Application-Key'); 
xhr.open('get', url, true); 
xhr.responseType = 'json'; 
xhr.onload = function() { 
    var status = xhr.status; 
    if (status == 200) { 
     // do what you need to do 
    } else { 
     // oh no an error occurred -.- 
    } 
}; 
xhr.send(); 
+0

這不起作用,因爲我沒有發出普通的http請求,我只是調用connect函數signalR框架,它顯然不允許設置請求標頭,無論如何,謝謝。 – Kira