So I have implemented my own custom membership provider, currently only overwriting ValidateUser(). I also have signalr working, currently just a simple method that calls send message and then sends it out to all listeners. I would like to add some validation checking so that this command cannot be run on its own. So far I have found you can do this using: 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");
}
}
}
My problem though is because I am currently using a custom membership provider value is false. Is there something else I should be using here instead?
Currently when I Login I execute:
[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", "");
}
What am I missing here? Do I need to store my own code to handle the session, I tried using FormsAuthentication.SetAuthCookie(model.UserName, true); which worked but I’m pretty sure its wrong. When I tried to introduce Roles by changing it to Context.User.IsInRole("Admin") it returned false. even though I used the below User model (which when debugging never gets to this method):
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;
}
}
I’m pretty confident I am missing something with this, any ideas?
Using
FormsAuthentication.SetAuthCookie()after you’ve validated the user is perfectly OK, the defaultAccountControllercreated by the MVC3 template does exactly the same.The reason why your call to
Context.User.IsInRole()doesn’t work is because that won’t invoke your customUserclass (the framework doesn’t know about it), instead it will try to get the roles via aRoleProvider. You need to build a custom provider and hook it up in the Web.config like you did with the membership provider.