是的,您可以访问数据库!在Configure 方法中运行的代码可以访问在ConfigureServices 方法中添加的任何服务,包括数据库上下文等内容。
例如,如果您有一个简单的实体框架上下文:
using Microsoft.EntityFrameworkCore;
using SimpleTokenProvider.Test.Models;
namespace SimpleTokenProvider.Test
{
public class SimpleContext : DbContext
{
public SimpleContext(DbContextOptions<SimpleContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
}
}
然后你把它添加到ConfigureServices:
services.AddDbContext<SimpleContext>(opt => opt.UseInMemoryDatabase());
然后,你可以在设置中间件时访问它:
var context = app.ApplicationServices.GetService<SimpleContext>();
app.UseSimpleTokenProvider(new TokenProviderOptions
{
Path = "/api/token",
Audience = "ExampleAudience",
Issuer = "ExampleIssuer",
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
IdentityResolver = (username, password) => GetIdentity(context, username, password)
});
并稍微改写GetIdentity方法:
private Task<ClaimsIdentity> GetIdentity(SimpleContext context, string username, string password)
{
// Access the database using the context
// Here you'd need to do things like hash the password
// and do a lookup to see if the user + password hash exists
}
我是原始样本的作者。抱歉一开始不清楚!我尝试以一种易于提供您自己的功能的方式编写IdentityResolver 委托——例如与您自己的数据库集成(如上所述),或将其连接到 ASP.NET Core Identity。当然,您也可以随意丢弃我的代码并做一些更好的事情。 :)