Reputation: 5866
I have done custom authentication system by following this example and it works. my code is like below. I am wondering how I should control if the user is authenticated in other Actions, lets say if users goes to /Profile/Index?
I have tried HttpContext.User and User.Identity but didnt work.
[HttpPost]
public ActionResult Login(string username, string password)
{
if (new UserManager().IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[] {
new Claim(ClaimTypes.NameIdentifier, username),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,username)
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
ModelState.AddModelError("", "invalid username or password");
return View();
}
this is my Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Upvotes: 2
Views: 3110
Reputation: 118937
You are not setting up authentication in your Owin pipeline. The easiest way is to add a file like the one below. Call it IdentityConfig.cs
and put it in the App_Start
folder:
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
//This line tells Owin which method to call
[assembly: OwinStartup(typeof(TokenBasedAuthenticationSample.IdentityConfig))]
namespace TokenBasedAuthenticationSample
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
//Here we add cookie authentication middleware to the pipeline
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/login"),
});
}
}
}
Upvotes: 2