javascript - 从 JS 客户端在 SignalR 控制台应用程序上进行身份验证

标签 javascript c# asp.net angularjs signalr

以下场景/我的解决方案包括以下内容:

项目一:(SELF HOST) 我有一个 SignalR 控制台应用程序,它处理包括身份验证过程在内的逻辑(使用 EF 查询数据库).
项目二:(CLIENT) 我有一个带有 AngularJS 客户端的 ASP.Net web 应用程序

到目前为止,我可以很好地与集线器通话。问题是,我似乎无法进行身份验证。我尝试了很多我发现的东西,但没有一个奏效。他们中的大多数甚至不适用于我的问题..

目前我已经将我的项目剥离回到基础,我有以下代码:

启动类:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);
        app.MapSignalR();
    }
}

我的中心:

[HubName("systemHub")]
public class systemHub : Hub
{

    public void Authenticate(String pLogin, String pPassword)
    {
        User curUser = new AuthManager().Authenticate(pLogin, pPassword);
//this is where I'd want to send the auth cookie or whatever and contact the "loginCallback" function in my client
    }

    [Authorize]
    public void Hello(String pMessage)
    {
        Clients.All.callbackFunc(pMessage);
    }
}

Js客户端:

    hinagApp.controller('hinagController', function ($scope) {
    $(document).ready(function () {
        var conURL = 'http://localhost:8080/signalr';
        $.getScript(conURL + '/hubs', function () {
            $.connection.hub.url = conURL;
            var lHub = $.connection.systemHub;

            lHub.client.callbackFunc = function(pM){
                alert(pM);
            }

            lHub.client.loginCallback = function (pSuccess) {
                if (pSuccess) {
                    //if logged in
                    lHub.server.hello("test");
                }
                else {
                    alert("fail");
                }
            }

            $('#loginbutton').click(function () {
                lHub.server.authenticate($('#input_login').val(), $('#input_pass').val());
            });

            $.connection.hub.start();
        });
    })
});

最佳答案

我最近遇到了类似的问题。如果我没理解错的话,您想在信号服务器应用程序上进行身份验证。 Signalr 可以很好地接受标准的网络请求。

将身份验证类型设置为 cookie:

        CookieAuthenticationOptions lOptions = new CookieAuthenticationOptions()
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
            LoginPath = new PathString("/Auth/Login"),
            LogoutPath = new PathString("/Auth/Logout"),
        };

        app.UseCookieAuthentication(lOptions);

如果用户想登录,设置你想使用的声明

var lForm = await context.Request.ReadFormAsync();
                    if (!String.IsNullOrEmpty(lForm["input_login"]) && !String.IsNullOrEmpty(lForm["input_pass"]))
                    {
                        //Benutzer authentifizieren
                        var lAuthenticatedUser = new UserManager().Authenticate(lForm["input_login"], lForm["input_pass"]);
                        if (lAuthenticatedUser != null)
                        {
                            //Existiert der Nutzer legen wir die Claims an
                            ClaimsIdentity lIdentity = new ClaimsIdentity(lOptions.AuthenticationType);
                            lIdentity.AddClaim(new Claim(ClaimTypes.Name, lAuthenticatedUser.Username));
                            lIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, lAuthenticatedUser.InternalUserId.ToString()));
                            lIdentity.AddClaim(new Claim(ClaimTypes.SerialNumber, context.Request.RemoteIpAddress));

                            //Und zum Schluss einloggen
                            context.Authentication.SignIn(lIdentity);

                            //Und auf die Spieleseite weiterleiten
                            context.Response.Redirect(BLL._Configuration.HinagGameURL);
                        }
                    }

如果您想提供登录页面,您可以这样做(例如,_Authpage 是您的页面字符串)

                else if (context.Request.Path.Value == "/Auth/")
            {
                if (context.Authentication.User != null)
                    context.Response.Redirect(BLL._Configuration.HinagGameURL);


                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync(_Authpage);
            }

如果用户需要其他任何东西(比如你的授权页面中的额外样式文件)

                else
            {
                await next();
            }

所有这些都属于您的 Startup。

关于javascript - 从 JS 客户端在 SignalR 控制台应用程序上进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744127/

相关文章:

javascript - NodeJs 对每个返回的 MySql 结果对象执行操作

c# - 无法更新 JToken 值

c# - 上传带有元数据的文件

javascript - 如何使用 JavaScript 获取 GridView 列的总和

c# - 使用 LINQ,如何限制根据子表属性检索的行?

javascript - 表排序器列显示/隐藏功能

javascript - 在矩形 Canvas 中创建彩虹效果

c# - MVC QueryString 到动态对象

asp.net - VS2010渲染控件JS很尴尬

c# - 如何在 Visual Studio 诊断工具窗口中切换进程?