我按照此 example 完成了自定义身份验证系统它有效。我的代码如下所示。我想知道如何控制用户是否在其他操作中进行身份验证,假设用户是否转到/Profile/Index?
我尝试过 HttpContext.User 和 User.Identity 但没有成功。
[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();
}
这是我的 Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
最佳答案
您没有在 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"),
});
}
}
}
关于c# - 如何在 MVC 中检查用户是否经过身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905372/