简体   繁体   English

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

[英]Custom Auth using OWIN on Asp Mvc

I am trying to create a login screen using owin on Asp MVC. 我试图在Asp MVC上使用owin创建一个登录屏幕。 This is the code that is in the controller. 这是控制器中的代码。

I have even tried hard coding the values but I still get a 401 when I try enter the dashboard after login. 我甚至尝试过对硬编码进行硬编码,但在登录后尝试进入仪表板时仍然会得到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();
    }

My startup file is empty am I missing something here 我的启动文件是空的,我在这里遗漏了一些东西

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

    }
}

Yes, you missed the Owin Cookie Configuration on Startup class: 是的,你错过了Startup类的Owin Cookie配置:

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

Install Nuget Package Microsoft.Owin.Security.Cookies then you are good to go 安装Nuget Package Microsoft.Owin.Security.Cookies然后你很高兴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM