WebAPI& SignalR Web应用程序 - Authenticating&授权

时间:2015-09-04 11:06:41

标签: asp.net authentication cookies asp.net-web-api signalr

我有一个WebAPI解决方案,我使用token authentication,所以流程如下:

  • 用户尝试使用usernamepassword
  • 登录
  • 如果凭据正确,则会为他提供一个令牌,以便在以下请求中使用(放在AJAX请求的标头中)。

现在SignalR开始发挥作用。由于它使用WebSockets,因此您无法传递标头。 在寻找解决方案时,我发现了以下内容:

  1. 实际上将标题传递给SignalR - 不是一个选项,因为它强制SignalR使用longPolling
  2. $.signalR.ajaxDefaults.headers = { Authorization: "Bearer " + token };

    1. 将用于验证token次呼叫的WebAPI作为query string /传递,或将其存储在SignalR的Cookie中,然后以某种方式创建提供商将令牌展开并扩展为标识。 I followed this blog post但我似乎错过了一些东西。

    2. 再次将令牌作为query string /或Cookie传递,但这次要创建自定义Authorize AttributeAuthorize SignalR个中心或方法。 Again a blog post about this.此解决方案的问题在于令牌上的Unprotect方法。

    3. 最终和最简单的解决方案是同时启用cookie authentication,继续使用bearer token authentication进行WebAPI次呼叫,并让OWIN Middleware授权呼叫集线器。 (这个解决方案确实有效)。

    4. 现在,问题在于WebAPI Individual User Accounts应用程序的默认模板使用AJAX(因此使用令牌身份验证),每当我向API发送public partial class Startup { public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static string PublicClientId { get; private set; } // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.UseCookieAuthentication(new CookieAuthenticationOptions()); PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; app.UseOAuthBearerTokens(OAuthOptions); } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } 请求时它还发送cookie。

          config.SuppressDefaultHostAuthentication();
          config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
      
      Authorization: Bearer 2bTw5d8Vf4sKR9MNMqZsxIOPHp5qtXRTny5YEC_y7yWyrDLU0__q8U8Sbo7N7XBjPmxZXP18GRXjDVb3yQ9vpQnWXppRhVA8KDeGg2G5kITMxiOKvGMaKwyUGpORIeZ0UHyP9jA2fX9zPwzsCqHmq-LoGKls0MQNFjXgRGCCCvro5WPMAJcLs0kUoD_2W_TOTy9_T-koobw-DOivnazPo2Z-6kfXaIUuZ1YKdAbcSJKzpyPR_XrCt4Ma2fCf-LcpMPGo4gDFKfxWdId0XtfS9S-5cXmmOmGM4Y6MkAUK8O9sZlVrpmpvV0hjXF2QwfLtQViPyEctbTr1vPBNn014n60APwGSGnbUJBWMvJhqcjI5pWoubCmk7OHJrn052U_F3bDOi2ha1mVjvhVY1XMAuv2c3Pbyng2ZT_VuIQI7HjP4SLzV6JjRctfIPLEh67-DFp585sJkqgfSyM6h_vR2gPA5hDocaFs73Qa22QMaLRrHThU0HM8L3O8HgFl5oJtD
      Referer: http://localhost:15379/index.html
      Accept-Encoding: gzip, deflate, sdch
      Accept-Language: en-US,en;q=0.8,ro;q=0.6
      Cookie: .AspNet.Cookies=E71BnnTMv8JJ4hS9K46Y2yIbGMQCTS4MVBWBXezUYCSGXPbUPNZh98Q0IElQ0zqGyhB7OpYfdh10Kcy2i5GrWGSiALPPtOZUmszfAYrLZwG2JYiU5MSW80OGZVMY3uG2U1aqvvKJpv7eJwJSOoS4meD_3Qy8SwRzTg8feZArAE-REEXSsbPfq4jQBUUbxfDAyuPVRsLNfkn4oIAwZTs85IulRZI5mLnLqOS7VLejMGIWhkuyOWvvISu1pjsP5FMDXNwDkjv2XCaOpRzZYUxBQJzkcdpDjwW_VO2l7HA263NaG_IBqYpLqG57Fi-Lpp1t5Deh2IRB0VuTqAgrkwxifoBDCCWuY9gNz-vNjsCk4kZc8QKxf7el1gu9l38Ouw6K1EZ9y2j6CGWmW1q-DobaK9JXOQEPm_LGyaGPM5to2vchTyjuieZvLBAjxhLKnXdy34Z7MZXLVIwmpSmyPvmbIuH9QzOvTWD-I1AQFJyCDw8
      

      即使我这样做了:

      SignalR

      您是否看到了使用令牌身份验证对1 bag of words 2 bag words of 3 of bag words 4 of words bag 5 words bag of 6 words of bag 进行身份验证的更简单方法?这种最终方法(如果我设法禁止发送带有请求的cookie)是否适用于生产?

1 个答案:

答案 0 :(得分:1)

在处理该特定项目时,我最终只使用了cookie身份验证和CSRF,但我仍然有兴趣了解如何使用承载令牌身份验证来验证WebApi和SignalR。

For a working sample, please see this GitHub repository.

我最终创建了一个OAuthBearerTokenAuthenticationProvider类,尝试从cookie中检索令牌。

public class OAuthBearerTokenAuthenticationProvider : OAuthBearerAuthenticationProvider
    {
        public override Task RequestToken(OAuthRequestTokenContext context)
        {
            var tokenCookie = context.OwinContext.Request.Cookies["BearerToken"];

            if (!String.IsNullOrEmpty(tokenCookie))
                context.Token = tokenCookie;

            return Task.FromResult<object>(null);
        }
    }

以下是Startup类中处理身份验证的方法:

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

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
        {
            Provider = new OAuthBearerTokenAuthenticationProvider()
        });

    }

For a working sample, please see this GitHub repository.

希望这在某些方面对某人有所帮助。