2017-08-02 43 views
1

在我的Web API 2項目中,我有基於JWT的身份驗證。配置是SignalR 2.0中的IAuthenticationFilter

var config = new HttpConfiguration(); 
    app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions {/**/}); 
    config.Filters.Add(new MyAuthenticationFilter()); 
    app.UseWebApi(config); 
    app.UseCors(CorsOptions.AllowAll); 
    app.MapSignalR(); 

MyAuthenticationFilter建立了基於傳入智威湯遜自定義主要並將其附加到一個請求,以致在我的控制器動作,我可以訪問它this.User。一切工作正常,除了過濾器的SignalR請求忽略:

public class MyHub : Hub { 
    public override Task OnConnected() { 
     // here Context.User is ClaimsPrincipal which contain a JWT from Authorization header 
     // I expect it to be MyCustomPrincipal 
     return base.OnConnected(); 
    } 
} 

爲什麼IAuthenticationFiltter被忽略?我如何解決這個問題?

回答

1

你不能在signalR頭上使用jwt。用qs發送jwt(查詢字符串)並在下面編碼的api上添加一些定製。

App_Start/Startup.Auth.cs

public void ConfigureAuth(IAppBuilder app) 
     { 
      // SignalR Auth0 custom configuration. 
      app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() 
      { 
       Provider = new OAuthBearerAuthenticationProvider() 
       { 
        OnRequestToken = context => 
        { 
         if (context.Request.Path.Value.StartsWith("/signalr")) 
         { 
          string bearerToken = context.Request.Query.Get("token"); 
          if (bearerToken != null) 
          { 
           string[] authorization = new string[] { "bearer " + bearerToken }; 
           context.Request.Headers.Add("Authorization", authorization); 
          } 
         } 

         return null; 
        } 
       } 
      }); 
    } 

和您使用集線器授權屬性

[Authorize] 

public class MyHub:Hub