在Asp Mvc上使用OWIN进行自定义验证

时间:2016-06-08 14:25:43

标签: c# asp.net-mvc owin

我正在尝试使用Asp MVC上的owin创建登录屏幕。 这是控制器中的代码。

我甚至尝试过对这些值进行硬编码,但在登录后尝试进入仪表板时仍然会得到401.

 [HttpPost]
    public ActionResult Login(string username, string password)
    {
        int userId = 0;
        string role = string.Empty;

        if (new UserManager().IsValid(username, password, ref userId, ref role))
        {
            var ident = new ClaimsIdentity(
              new[] { 
          // adding following 2 claim just for supporting default antiforgery provider
          new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
          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),

          // optionally you could add roles if any
          new Claim(ClaimTypes.Role, role)

              },
              DefaultAuthenticationTypes.ApplicationCookie);

            HttpContext.GetOwinContext().Authentication.SignIn(
               new AuthenticationProperties { IsPersistent = false }, ident);
            return RedirectToAction("Dashboard"); // auth succeed 
        }
        // invalid username or password
        ModelState.AddModelError("", "invalid username or password");
        return View("Index", "_LayoutUnAuthorised");
    }

    [Authorize(Roles = "Default")]
    public ActionResult Dashboard()
    {



        return View();
    }

我的启动文件是空的,我在这里遗漏了一些东西

public class Startup
{
    public void Configuration(IAppBuilder app)
    {

    }
}

1 个答案:

答案 0 :(得分:4)

是的,您错过了Startup类的Owin Cookie配置:

public void Configuration(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationMode = AuthenticationMode.Active,
        AuthenticationType = "ApplicationCookie",
        LoginPath = new PathString("/Account/LogOn"),
    });
}

安装Nuget Package Microsoft.Owin.Security.Cookies然后你就可以了