2016-08-02 8 views
9

私は最近、.NET Core Web APIを開発しています。私はちょうどhttps://stormpath.com/blog/token-authentication-asp-net-coreのガイドに従って、JWTを使用して認証を試みました。ASP.NET Coreで起動時にデータベースにアクセスできますか?

GetIdentityのハードコードされたユーザー名とパスワードをDBクエリに置き換えて、このファイル内からDBにアクセスする方法がわからないときは、すべてうまくいっていました。

私が言及しています方法は次のように私の質問がある行に以下のリンク70 https://github.com/nbarbettini/SimpleTokenProvider/blob/master/test/SimpleTokenProvider.Test/Startup.Auth.cs

に示されています。

  1. ここでデータベースにアクセスできますか?もしそうなら、どのように?
  2. これは、GetIdentityメソッドがどこにあるか、より良い方法がありますか?

答えて

10

はい、データベースにアクセスできます。 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方法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アイデンティティにJWTを追加している場合は、代わりにdbcontextのsigninmanagerを渡すことがあります。 (userManager )) – xcud

+0

@xcudこれはまさに私がやろうとしているのですが、「スコープされたサービス 'Microsoft.AspNetCore.Identity.UserManager'を解決できません」というエラーが表示されます。私はここで何が欠けているのですか? –

0

他のレベルでは間違っているかもしれませんが、私が見つけた解決策はスコープを作成することです。

私はその後、GetIdentityにスコープを使用して、アプリの代わりGetIdentityでCTXを渡さ:

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[] { })); 
     } 
    } 
    } 
関連する問題