2016-08-02 84 views
9

我最近一直在研究.NET Core web API。我剛剛嘗試使用JWT進行身份驗證,請遵循https://stormpath.com/blog/token-authentication-asp-net-core上的指南。我可以在ASP.NET Core啓動期間訪問數據庫嗎?

一切都很順利,直到我必須用DB查詢替換GetIdentity方法中的硬編碼用戶名和密碼,並意識到我不知道如何從此文件中訪問數據庫!

的方法,我指的是顯示在下面的鏈接上線70 https://github.com/nbarbettini/SimpleTokenProvider/blob/master/test/SimpleTokenProvider.Test/Startup.Auth.cs

我的問題如下。

  1. 我可以在這裏訪問數據庫嗎?如果是這樣如何?
  2. 這應該是GetIdentity方法所在,還是有更好的方法?

回答

10

是的,你可以訪問數據庫!在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方法a litt le:

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。當然,你可以自由地扔掉我的代碼並做更好的事情。 :)

+3

如果你剛加入智威湯遜到ASPNET身份,你可以通過替代的DbContext的signinmanager: var userManager = app.ApplicationServices .GetService(typeof(UserManager )) – xcud

+0

@xcud這正是我想要做的,但得到一個錯誤「無法解決範圍服務'Microsoft.AspNetCore.Identity.UserManager'」,我在這裏錯過了什麼? –

0

我可能在某些其他級別上是錯誤的,但我找到的解決方案是創建一個範圍。

我通過應用程序,而不是在GetIdentity的CTX,然後在GetIdentity使用範圍:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) { 
    if (serviceScope.ServiceProvider.GetService<YourAppDbContext>() != null) 
    { 
     var ctx = serviceScope.ServiceProvider.GetService<YourAppDbContext>(); 

     if (AnAuthenticateMethodHereMaybe(ctx, username, password)) { 
     return Task.FromResult(new ClaimsIdentity(new 
GenericIdentity(username, "Token"), new Claim[] { })); 
     } 
    } 
    } 
相關問題