如何在静态主函数中使用数据库表验证用户名和密码?

huangapple go评论56阅读模式
英文:

How do I validate username and password using database table in the static main?

问题

我正在尝试在ASP.NET Web API中实现身份验证。为了实现这一目标,我正在使用idunno.Authentication.Basic。我的主要目标是将授权用户的表与用户输入进行比较。不幸的是,我遇到了一个问题,我无法在静态主函数中实例化UserContext类。

我尝试传递配置选项,但它给我返回以下错误:

Severity Code Description Project File Line Suppression State
无法从'Microsoft.Extensions.DependencyInjection.IServiceCollection'转换为'Microsoft.EntityFrameworkCore.DbContextOptions<minimalAPI.models.UserContext>'

以下是程序.cs文件中的代码:


public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    // 向容器添加服务。
    builder.Services.AddDbContext<UserContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalAPIDatabase"))); // 使用数据库连接字符串在服务容器中注册UserContext类。这允许应用程序使用UserContext实例来访问和操作数据库中的数据。

    // 使用idunno.Authentication.Basic
    builder.Services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
        .AddBasic(options =>
        {
            options.Realm = "Basic Authentication";
            options.Events = new BasicAuthenticationEvents
            {
                OnValidateCredentials = async context =>
                {
                    string username = context.Username;
                    string password = context.Password;

                    var options = builder.Services.ConfigureOptions(null);

                    UserContext _userContext = new UserContext(options);

                    AuthUser? user = await _userContext.AuthUsers.FirstOrDefaultAsync(u => u.UserName == username && u.Password == password);

                    if (user != null)
                    {
                        var claims = new[]
                        {
                            new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                            new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                        };

                        context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                        context.Success();
                    }

                    return Task.CompletedTask;
                }
            };
        });
}

``````````````````````````````````````````````````````````````````````````````````````````````````

以下是UserContext类:

````````````````````````````````````````````````````````````````````````````````````

public class UserContext : DbContext
{
    public UserContext(DbContextOptions<UserContext> options) : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<AuthUser> AuthUsers { get; set; }
}

``````````````````````````````````````````````````````````````````````````````````

<details>
<summary>英文:</summary>

I am currently attempting to implement authentication in an ASP.NET Web API. To achieve this, I am utilizing idunno.Authentication.Basic. My main objective is to compare the authorized user&#39;s table against the user input. Unfortunately, I have encountered an issue where I am unable to instantiate the UserContext class within the static main

I tried passing the Configure options, but it gave me the following error:

Severity	Code	Description	Project	File	Line	Suppression State
cannot convert from &#39;Microsoft.Extensions.DependencyInjection.IServiceCollection&#39; to &#39;Microsoft.EntityFrameworkCore.DbContextOptions&lt;minimalAPI.models.UserContext&gt;&#39;

Here is the code in the program.cs file:

public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddDbContext&lt;UserContext&gt;(options =&gt;
            options.UseSqlServer(builder.Configuration.GetConnectionString(&quot;MinimalAPIDatabase&quot;)));//registers the UserContext class in the service container with a database connection string. This allows the application to use the UserContext instance to access and manipulate data from the database.

        


        //uses idunno.Authentication.Basic
        builder.Services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme)
            .AddBasic(options =&gt;
            {
                options.Realm = &quot;Basic Authentication&quot;;
                options.Events = new BasicAuthenticationEvents
                {
                    OnValidateCredentials = async context =&gt;
                    {


                        string username = context.Username;
                        string password = context.Password;

                        var options = builder.Services.ConfigureOptions(null);
                        
                        UserContext _userContext = new UserContext(options);

                        AuthUser? user = await _userContext.AuthUsers.FirstOrDefaultAsync(u =&gt; u.UserName == username &amp;&amp; u.Password == password);

                        if (user != null)

                            if (user != null)
                            {
                                var claims = new[]
                                {
                                new Claim(ClaimTypes.NameIdentifier, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer),
                                new Claim(ClaimTypes.Name, context.Username, ClaimValueTypes.String, context.Options.ClaimsIssuer)
                                                };

                                context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
                                context.Success();
                            }

                        return Task.CompletedTask;
                    }
                };
            });

Here is the UserContext class:

````````````````````````````````````````````````````````````````````````````````````
public class UserContext : DbContext
    {       
        public UserContext(DbContextOptions&lt;UserContext&gt; options) : base(options)
        {
          
        }


        public DbSet&lt;User&gt; Users { get; set; }
        public DbSet&lt;AuthUser&gt; AuthUsers { get; set; }
    }
````````````````````````````````````````````````````````````````````````````````````	

</details>


# 答案1
**得分**: 2

在这行中出现了错误:

```
var options = builder.Services.ConfigureOptions(null);
```

您应该改为写这些行:

```
var optionsBuilder = new DbContextOptionsBuilder<UserContext>();
optionsBuilder.UseSqlServer(builder.Configuration.GetConnectionString("MinimalAPIDatabase"));
var options = optionsBuilder.Options;
```

<details>
<summary>英文:</summary>

you having error in this line    

    var options = builder.Services.ConfigureOptions(null);

instead you should write these lines 

    var optionsBuilder = new DbContextOptionsBuilder&lt;UserContext&gt;();
    optionsBuilder.UseSqlServer(builder.Configuration.GetConnectionString(&quot;MinimalAPIDatabase&quot;));
    var options = optionsBuilder.options;



</details>



huangapple
  • 本文由 发表于 2023年3月8日 16:23:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定