2017-05-17 84 views
5

我有這種使用最簡單形式的表單身份驗證的舊MVC5應用程序。只有一個存儲在web.config中的帳戶,沒有角色等Asp.Net核心 - 最簡單的可能的表單身份驗證

<authentication mode="Forms"> 
    <forms loginUrl="~/Login/Index" timeout="30"> 
    <credentials passwordFormat="Clear"> 
     <user name="some-user" password="some-password" /> 
    </credentials> 
    </forms> 
</authentication> 

登錄程序只是調用

FormsAuthentication.Authenticate(name, password); 

就是這樣。 在asp.net核心中是否有類似的東西(簡單來說)?

+0

認證不能和asp.net核心兼容。而是使用標識 –

回答

9

這不是簡單:)

  1. 在Startup.cs,配置方法。

    app.UseCookieAuthentication(options => 
    { 
        options.AutomaticAuthenticate = true; 
        options.AutomaticChallenge = true; 
        options.LoginPath = "/Home/Login"; 
    }); 
    
  2. 添加Authorize屬性以保護您想要保護的資源。

    [Authorize] 
    public IActionResult Index() 
    { 
        return View(); 
    } 
    
  3. 在Home Controller的Login Post操作方法中,寫入以下方法。

    var username = Configuration["username"]; 
    var password = Configuration["password"]; 
    if (authUser.Username == username && authUser.Password == password) 
    { 
        var identity = new ClaimsIdentity(claims, 
         CookieAuthenticationDefaults.AuthenticationScheme); 
    
        HttpContext.Authentication.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme, 
        new ClaimsPrincipal(identity)); 
    
        return Redirect("~/Home/Index"); 
    } 
    else 
    { 
        ModelState.AddModelError("","Login failed. Please check Username and/or password"); 
    } 
    

這裏是供您參考GitHub庫:https://github.com/anuraj/CookieAuthMVCSample與FormAuth

+0

我使用你的代碼,但是它在「Startup.cs,configure method」中給出一個錯誤「不能將lambda表達式轉換爲類型」。 –

+0

@SanyamiVaidya你正在使用哪個版本的asp.net核心? – Anuraj

+0

我使用的是1.0.1版本的asp.net核心 –