2016-06-08 46 views
2

我想在Asp MVC上使用owin創建一個登錄屏幕。 這是控制器中的代碼。在Asp Mvc上使用OWIN的自定義Auth

我甚至嘗試過對值進行硬編碼,但當我嘗試登錄後進入儀表板時,仍然收到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) 
    { 

    } 
} 

回答

3

是的,你錯過了Owin Cookie的配置上啓動類:

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

安裝NuGet包Microsoft.Owin.Security.Cookies那麼你很好去

相關問題