c# - 如何在 MVC 中检查用户是否经过身份验证

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我按照此 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/

相关文章:

c# - SQL Server Compact Edition-字节数组截断到长度为 8000 异常

asp.net - 有没有办法检测更新面板何时完成刷新?

asp.net-mvc - ASP.NET MVC 3 RC 2 客户端验证与全局化

c# - closedxml.report中的纵横表组合

c# - 无法使用 ASP.NET Core 从 JWT token 获取声明

c# - 在 C# 中创建部分(或有界)FileStream

asp.net - 为什么在 StateServer 模式下运行时会丢失 session ?

javascript、jQuery 和 ajax 函数在 asp.net MVC 中无法正常工作

c# - 使用 Javascript 在 MVC 中渲染部分 View

asp.net-mvc - 本地化的脚本包解决方案