gpt4 book ai didi

c# - 我可以在 ASP.NET Core 启动期间访问数据库吗?

转载 作者:IT王子 更新时间:2023-10-29 04:48:24 25 4
gpt4 key购买 nike

我最近一直在研究 .NET Core Web API。我刚刚按照 https://stormpath.com/blog/token-authentication-asp-net-core 上的指南尝试使用 JWT 进行身份验证.

一切都很顺利,直到我不得不用数据库查询替换 GetIdentity 方法中的硬编码用户名和密码,并意识到我不知道如何从这个文件中访问数据库!

我指的方法显示在下面第 70 行的链接中。 https://github.com/nbarbettini/SimpleTokenProvider/blob/master/test/SimpleTokenProvider.Test/Startup.Auth.cs

我的问题如下。

  1. 我可以在这里访问数据库吗?如果是,如何?
  2. 这应该是 GetIdentity 方法所在的位置,还是有更好的方法?

最佳答案

是的,您可以访问数据库!在 Configure 方法中运行的代码可以访问在 ConfigureServices 方法中添加的任何服务,包括数据库上下文等内容。

例如,如果您有一个简单的 Entity Framework 上下文:

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 委托(delegate)——例如与您自己的数据库集成(如上所述),或将其连接到 ASP.NET Core Identity。当然,您也可以随意丢弃我的代码并做一些更好的事情。 :)

关于c# - 我可以在 ASP.NET Core 启动期间访问数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728623/

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