gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:00:05 25 4
gpt4 key购买 nike

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

在 Configure() 方法中,我添加了 app.UseAuthentication();
当我登录并移动到使用注释 [Authorize] 的 Controller 类时,出现以下错误

An unhandled exception occurred while processing the request. InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or 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)

最佳答案

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

Use cookie authentication without ASP.NET Core Identity

下面的简单代码示例供您引用:

  • Startup.ConfigureServices方法,使用 AddAuthentication 创建身份验证中间件服务和 AddCookie方法:
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
    options.LoginPath = "/Account/Login";
    });

    并在 Configure 中启用中间件:
    app.UseAuthentication();
    app.UseAuthorization();
  • 您可以申请 [Authorize] protected Controller / Action 的属性。当用户未通过身份验证时,默认用户将被重定向到 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"));
  • 关于c# - 如何在没有数据库的情况下在 ASP.NET Core 中创建一个简单的登录并授权 Controller 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60520664/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com