[英]How to check if a user is authenticated in MVC
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? 我想知道如何控制用户是否在其他操作中通过了身份验证,可以说用户是否转到/ Profile / Index?
I have tried HttpContext.User and User.Identity but didnt work. 我尝试了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();
}
this is my Global.asax 这是我的Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
You are not setting up authentication in your Owin pipeline. 您没有在Owin管道中设置身份验证。 The easiest way is to add a file like the one below. 最简单的方法是添加一个类似于以下文件的文件。 Call it IdentityConfig.cs
and put it in the App_Start
folder: 将其App_Start
为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"),
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.