英文:
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'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 'Microsoft.Extensions.DependencyInjection.IServiceCollection' to 'Microsoft.EntityFrameworkCore.DbContextOptions<minimalAPI.models.UserContext>'
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<UserContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MinimalAPIDatabase")));//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 =>
{
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)
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<UserContext> options) : base(options)
{
}
public DbSet<User> Users { get; set; }
public DbSet<AuthUser> 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<UserContext>();
optionsBuilder.UseSqlServer(builder.Configuration.GetConnectionString("MinimalAPIDatabase"));
var options = optionsBuilder.options;
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论