首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在MVC中检查用户是否已通过身份验证

如何在MVC中检查用户是否已通过身份验证
EN

Stack Overflow用户
提问于 2017-01-28 09:03:54
回答 1查看 2.6K关注 0票数 2

我已经做了自定义认证系统通过遵循这个example,它是工作的。我的代码如下所示。我想知道我应该如何控制用户是否在其他操作中进行了身份验证,比如用户是否转到/Profile/Index?

我试过HttpContext.User和User.Identity,但不起作用。

代码语言:javascript
复制
[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

代码语言:javascript
复制
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-28 09:41:43

您没有在您的Owin管道中设置身份验证。最简单的方法是添加一个如下所示的文件。将其命名为IdentityConfig.cs,并将其放在App_Start文件夹中:

代码语言:javascript
复制
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"),
            });
        }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41905372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档