I'm trying to create a simple user authentication function but I just can't get it to work. Here is the code I'm working on:
public class LoginController : ApiController
{
private void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
public bool Login(string token)
{
//Check token
if (.....)
{
//Authenticate user
var identity = new GenericIdentity("Test user");
SetPrincipal(new GenericPrincipal(identity, new string[]{"Test role"}));
}
}
[Authorize]
public string TestFun()
{
return "Hello " + User.Identity.Name;
}
}
So, if I try to call method TestFun()
first, it returns error code 401 like it should.
However when I call method Login()
it should somehow save user credentials, but this is where I get lost, I just can't get it to work.
TestFun()
always returns error code 401 even if I call Login()
first.
If I try to put return "Hello " + User.Identity.Name;
in the Login()
function it returns correct username, but in the TestFun()
the user is not available.
I've even tried using Sessions and FormsAuthentication but I just can't get it to work, even on this really simple example.
Can someone please tell me what am I missing?
Thanks!