我已经按照以下示例完成了自定义身份验证系统,并且可以正常工作。我的代码如下。我想知道如何控制用户是否在其他操作中通过了身份验证,可以说用户是否转到/ 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"),
});
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句