如何在没有数据库的情况下在 ASP.NET Core 中创建一个简单的登录并授权控制器访问

sm1*_*101 2 c# asp.net-core

我正在使用 ASP.NET Core 3.1。如何在不使用数据库的情况下创建一个简单的基于 ASP.NET Core 的登录。假设我没有使用数据库,而是在 appsettings.json 中有登录用户名和密码。我可以轻松访问并获取 appsettings 值。但是我应该如何实现登录功能以及我应该如何在 startup.cs 中配置服务(在配置和配置服务中)。

在 Configure() 方法中,我添加了 app.UseAuthentication();

当我登录并移动到使用注释 [Authorize] 的 Controller 类时,出现以下错误

处理请求时发生未处理的异常。InvalidOperationException: 未指定 authenticationScheme,也未找到 DefaultChallengeScheme。可以使用 AddAuthentication(string defaultScheme) 或 AddAuthentication(Action configureOptions) 设置默认方案。Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Nan*_* Yu 7

首先,将用户的凭据存储到 appsettings.json 不是一个好主意。如果您想出于测试目的实现它,您可以使用 cookie 身份验证:

在没有 ASP.NET Core Identity 的情况下使用 cookie 身份验证

下面的简单代码示例供您参考:

  1. 在该Startup.ConfigureServices方法中,使用AddAuthentication和AddCookie方法创建身份验证中间件服务:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
            });
    
    Run Code Online (Sandbox Code Playgroud)

    并在Configure以下位置启用中间件:

    app.UseAuthentication();
    app.UseAuthorization();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您可以[Authorize]在受保护的控制器/操作上应用该 属性。当用户未通过身份验证时,默认用户将被重定向到 LoginPath 进行 cookie 身份验证。/Account/Login操作将显示用户名/密码文本框以收集用户的凭据。

  3. 用户输入凭据并单击提交按钮后,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");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    UserToLogin.cs :

    public class UserToLogin
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

    appsettings.json:

    {
        "Users": [
            {
                "UserName": "xxxxxxxx",
                "Password": "xxxxxxx"            
            },
            {
                "UserName": "xxxxxxxx",
                "Password": "xxxxxxxxxxxx"            
            }       
        ],           
    }
    
    Run Code Online (Sandbox Code Playgroud)

    并在 ConfigureServices 中注册:

    services.Configure<List<UserToLogin>>(Configuration.GetSection("Users"));
    
    Run Code Online (Sandbox Code Playgroud)