我已按照此example完成了自定义身份验证系统,但它确实有效。我的代码如下。我想知道如果用户在其他操作中进行身份验证我应该如何控制,让我们说如果用户进入/ Profile / Index?
我已经尝试过HttpContext.User和User.Identity但是没有用。
.slice(0,4)
这是我的Global.asax
[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();
}
答案 0 :(得分:2)
您没有在Owin管道中设置身份验证。最简单的方法是添加如下所示的文件。将其命名为IdentityConfig.cs
并将其放入App_Start
文件夹:
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"),
});
}
}
}