使用授权标头信号器

时间:2016-05-10 14:40:55

标签: c# authorization signalr

我正在使用signalR而我正试图让[Authorize]属性起作用。通过以下设置,我获得401 Unauthorized ..

在我启动Hub之前,我按照以下方式设置了授权:

$.signalR.ajaxDefaults.headers = { Authorization: 'Bearer ' + settingsService.getItem('authData').token }

我可以看到标题是在请求中发送的,如下所示:

  

授权:承载F0wGNa7cAwUjOFI27TDR_w7N4Ncmz66PGpsU1AH2AWt0Gdt39e2o4DGwPsBXTAlIwHrAF-YHE9I1KGLxfabE0QxpcY5mLn1gxGWStOSX_W5NaUQlRlpRu5k-s6YLH-vVjlakqap_YXbzPelZJOjwcz7Ea5VHcCUFQ5xDYYK0VJXDIqMwQXZPIyVtNVu1RyLLVj7iOZaMd-41gHKWNqFWJBmK5WkWw06dI4AWiifWJT_8v1WrFPCAzYfiT0U

我的中心:

[Authorize]
[HubName("myHub")]
public class DataHub : Hub {
    private static bool _isInitated;

    public DataHub() {
         //Do stuff
        }
    }
}

令牌的创建方式如下:

var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
        identity.AddClaim(new Claim("Username", "myname"));

        var properties = new AuthenticationProperties() {
            IssuedUtc = DateTime.UtcNow,
            ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan)
        };

        var ticket = new AuthenticationTicket(identity, properties);
        var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

        var response = new JObject(new JProperty("access_token", accessToken), new JProperty("expires_in", Startup.OAuthOptions.AccessTokenExpireTimeSpan.TotalMinutes));

        return Ok(new { token = response });

我错过了一些特别的东西吗?不是真的明白了。

1 个答案:

答案 0 :(得分:2)

如果这是其他人的问题我在这里得到了答案。在我的startup.cs中,我必须在Configuration方法中最后移动app.MapSignalR();。如下所示:

public class Startup {
    public void Configuration(IAppBuilder app) {
        CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
        GlobalHost.Configuration.DefaultMessageBufferSize = 100;
        ConfigureOAuth(app);
        app.MapSignalR();
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public void ConfigureOAuth(IAppBuilder app) {
        OAuthOptions = new OAuthAuthorizationServerOptions {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(7)
        };

        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

在我ConfigureOAuth(app);持续前......然后它无法正常工作