【问题标题】:signalr using custom membership provider使用自定义成员资格提供程序的信号器
【发布时间】:2012-09-07 00:32:59
【问题描述】:

所以我已经实现了我自己的自定义会员提供程序,目前只覆盖了 ValidateUser()。我也有信号器工作,目前只是一个简单的方法,它调用发送消息,然后将其发送给所有听众。我想添加一些验证检查,以便该命令不能单独运行。到目前为止,我发现您可以使用以下方法执行此操作:Context.User.Identity.IsAuthenticated

[HubName("messageController")]
public class MessageController : Hub
{
    public void SendMessage(string message)
    {
        if (Context.User.Identity.IsAuthenticated)      // this line not working
        {
            Clients.addMessage(message);
        }
        else
        {
            Clients.addMessage("not authenticated");
        }
    }
}

我的问题是因为我目前使用的自定义会员提供程序值为 false。我应该在这里使用其他东西吗?

目前当我登录时执行:

    [AllowAnonymous]
    [HttpPost]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if(Membership.ValidateUser(model.UserName, model.Password))
        {
            // Need something here to actually set the logged in user
        }
        return RedirectToAction("Index", "");
    }

我在这里缺少什么?我是否需要存储自己的代码来处理会话,我尝试使用FormsAuthentication.SetAuthCookie(model.UserName, true);,它有效,但我很确定它错了。当我尝试通过将角色更改为Context.User.IsInRole("Admin") 来引入角色时,它返回了错误。即使我使用了以下用户模型(调试时从未使用此方法):

public class User : IPrincipal
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }


    public long UserID;
    public string Name;
    public string ConnectionId;

    public virtual IIdentity Identity
    {
        get;
        set;
    }

    public virtual bool IsInRole(string role)
    {
       return true;
    }

}

我很确定我错过了一些东西,有什么想法吗?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 signalr


    【解决方案1】:

    在验证用户完全正常后使用FormsAuthentication.SetAuthCookie(),MVC3 模板创建的默认AccountController 完全相同。

    您对 Context.User.IsInRole() 的调用不起作用的原因是因为它不会调用您的自定义 User 类(框架不知道它),而是会尝试通过RoleProvider。您需要构建一个自定义提供程序并将其连接到 Web.config 中,就像您对成员资格提供程序所做的那样。

    【讨论】:

    • 感谢这完美的工作。在看到评论之前,我实际上已经实现了这一点,但谢谢。唯一令人困惑的另一件事是,当您调用 Context.User.IsInRole() 它调用 RoleProvider.GetRolesForUser 它不调用 RoleProvider.IsUserInRole()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多