Reputation: 5389
I'm working on writing a simple login page + SignalR chat room for my website with vNext beta8
. Unfortunately, I'm having a very difficult time understanding how claims and authentication work.
All I am trying to do is authenticate a user and set Context.User
to their identity, so it can be accessed in SignalR. With the way I have it now, though, Context.User
is null everywhere, so SignalR isn't even the meat of this question.
Here's the relevant bits of code for this issue:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession();
services.AddCaching();
services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
app.UseSignalR();
}
Login Web API controller method with default values provided, skipping password/authentication checks, and setting the session, which works. LoginUserInfo
is just a small class to receive a username/password for logging in.
[HttpPost]
public string Login(LoginUserInfo info)
{
kUser user = new kUser();
user.Name = "Test user";
//This is where I am completely missing the point of something
Context.User = new ClaimsPrincipal(user);
}
kUser - this class is incomplete, I'm assuming that AuthenticationType
and IsAuthenticated
don't come into affect here, since the exception is never thrown.
[Serializable]
public class kUser : IIdentity
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string AuthenticationType
{
get { return "MongoDB"; }
}
public bool IsAuthenticated
{
get
{
//If ID exists in database
throw new NotImplementedException();
}
}
}
Research leads me to many different ways to accomplish setting Context.User
and having it available across the entire application. Some guides point to FormsAuthentication
, which doesn't seem to exist in ASP.NET 5, some talk about setting user IDs to each thread, and some detail how to write an entire service provider for authentication.
All I want is an extremely basic login procedure - no Remember Me style cookies, nothing fancy. Just type in username/password, and the server remembers you for your session. Where am I going wrong, and what am I missing?
Upvotes: 1
Views: 979
Reputation: 19598
You need to do something like this
var claims = new[] { new Claim("name", authUser.Username), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
Context.Authentication.SignIn(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
More details - https://github.com/anuraj/CookieAuthMVCSample
I didn't verified the code with latest runtime.
Upvotes: 2