Asp.Net Core-最简单的表单身份验证 [英] Asp.Net Core - simplest possible forms authentication
问题描述
我有这个旧的MVC5应用程序,它以最简单的形式使用表单身份验证. web.config中仅存储一个帐户,没有角色等.
I have this old MVC5 application that uses forms authentication in the simplest possible form. There is only one account stored in web.config, there are no roles etc.
<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核心中是否有类似的内容(在简单性方面)?
And that's it. Is there something similar (in terms of simplicity) in asp.net core?
推荐答案
不是那么简单:)
-
在Startup.cs中,配置方法.
In the Startup.cs, configure method.
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.LoginPath = "/Home/Login";
});
添加授权属性以保护要保护的资源.
Add Authorize attribute to protect the resources you want to secure.
[Authorize]
public IActionResult Index()
{
return View();
}
在主控制器"中的登录后"操作方法中,编写以下方法.
In the Home Controller, Login Post action method, write the following method.
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
Here is the github repo for your reference : https://github.com/anuraj/CookieAuthMVCSample
这篇关于Asp.Net Core-最简单的表单身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!