我正在使用ASP. NET Core 3.1。如何在不使用数据库的情况下创建一个简单的基于ASP. NET Core的登录。让我们说,而不是使用数据库,我有登录用户名和密码在appsettings.json.我可以很容易地访问和获取应用程序设置值。但是我应该如何实现登录功能,以及我应该如何在startup.cs中配置服务(在配置和配置服务中)。
在配置()方法中,我添加了应用。用户身份验证
当我登录并移动到使用注释[Authorize]的控制器类时,我得到以下错误
处理请求时发生未处理的异常。无效操作异常:未指定身份验证方案,也未找到默认挑战方案。默认的方案可以使用Add身份验证(字符串默认方案)或Add身份验证(操作配置选项)来设置。微软。AspNetCore.认证。身份验证服务。挑战同步(HttpContext上下文,字符串方案,身份验证属性)Microsoft.AspNetCore.授权。AuthorizationMiddleware.调用(HttpContext上下文)Microsoft.AspNetCore.诊断。DeveloperExceptionPageMiddleware.调用(HttpContext上下文)
首先,将用户的凭据存储到appsettings.json不是一个好主意。如果您想实现测试目的,您可以使用cookie身份验证:
不使用ASP. NET核心标识使用cookie身份验证
下面是一个简单的代码示例,供您参考:
>
在Startup.ConfigureServices
方法中,使用AddAuthentication
和AddCookie
方法创建身份验证中间件服务:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
});
并在配置中启用中间件:
app.UseAuthentication();
app.UseAuthorization();
您可以对受保护的控制器/操作应用[Authorize]
属性。当用户未通过身份验证时,defalut用户将重定向到LoginPath进行cookie身份验证<代码>/Account/Login操作将显示用户名/密码文本框以收集用户凭证。
用户输入凭证并单击提交按钮后,post方法将检查凭证并创建cookie:
public class AccountController : Controller
{
private readonly IOptions<List<UserToLogin>> _users;
public AccountController (IOptions<List<UserToLogin>> users)
{
_users = users;
}
[HttpPost]
public async Task<IActionResult> Login(UserToLogin userToLogin)
{
var user = _users.Value.Find(c => c.UserName == userToLogin.UserName && c.Password == userToLogin.Password);
if (!(user is null))
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,userToLogin.UserName),
new Claim("FullName", userToLogin.UserName),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
RedirectUri = "/Home/Index",
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
return Redirect("/Accout/Error");
}
}
UserToLogin.cs:
public class UserToLogin
{
public string UserName { get; set; }
public string Password { get; set; }
}
appsettings.json:
{
"Users": [
{
"UserName": "xxxxxxxx",
"Password": "xxxxxxx"
},
{
"UserName": "xxxxxxxx",
"Password": "xxxxxxxxxxxx"
}
],
}
并在ConfigureServices中注册:
services.Configure<List<UserToLogin>>(Configuration.GetSection("Users"));