从IIS托管的MVC应用程序调用时,Context.User在自托管SignalR中心为空

时间:2015-04-16 22:00:14

标签: asp.net-mvc asp.net-mvc-5 signalr authorize self-hosting

我有一个IIS托管的MVC 5应用程序,它使用Asp.Net Identity和OWIN通过.AspNet.ApplicationCookie进行身份验证。从其中一个观点来看,我通过SignalR JS客户端在自托管SignalR集线器(在同一服务器上运行)上调用长时间运行的方法。这些调用都按预期工作。我现在想用[授权(角色="管理员")]装饰我的集线器。事实证明这是有问题的。在hub方法中设置断点会显示Context.User为null,即使.AspNet.ApplicationCookie明显位于Context.RequestCookies中。

以下是集线器的引导程序(在Windows服务中自托管):

app.Map("/signalr", map =>
{
    map.UseCors(CorsOptions.AllowAll);
    map.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
    });

    var hubConfiguration = new HubConfiguration();
    map.RunSignalR(hubConfiguration);
});

以下是Web应用程序的auth配置(在IIS中托管):

// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(UserAccountContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

问题1:在上述方案中是否可以使用[授权]?如果是这样,怎么样?

问题2:将自托管集线器合并到IIS托管应用中会不会更好?如果是这样,IIS下长期运行的集线器方法是否存在任何问题?

更新1 我尝试将TicketDataFormat = new TicketDataFormat(new MachineKeyDataProtector("ASP.NET Identity"))添加到我的集线器配置上的CookieAuthenticationOptions,但这没有用。当然看起来这应该比它更容易。

1 个答案:

答案 0 :(得分:0)

我最终将我的自托管中心移动到我的ASP.Net应用程序中,它运行得很好。这比在这个SO问题OWIN Self-Host CookieAuthentication & Legacy .NET 4.0 Application / FormsAuthenticationTicket

中实现变通方法更容易,更易于维护