2016-04-26 9 views
1

空のプロジェクトから開始した既存のMVC 5アプリケーションに認証を追加するための認証を追加しようとしています。個々のユーザーアカウントを持つ新しいWebAPIプロジェクトを開始したので、どのように構成されているかを確認できました。私は、認証に関連するコードをコピーし、名前空間とクラス名をリファクタリングしました。以下のコードでは、最初の行var identityContext = context.Get<IdentityDbContext>()はnullを返し、2番目の行var userStore = new UserStore<AdminAppUser>(identityContext)はnullパラメータのためにエラーをスローします。IOwinContext.Get <DbContext>()がnullを返す

私はMVC認証には非常に慣れていて、すべての部分がどのように適合しているかをよく理解していないため、おそらく十分なコードが含まれていませんでした。より多くのコードを含める必要がある場合は、どの部分が有用かを教えてください。ありがとうございました!

public static AdminAppUserManager Create(IdentityFactoryOptions<AdminAppUserManager> options, IOwinContext context) 
    { 

     var identityContext = context.Get<IdentityDbContext>(); 
     var userStore = new UserStore<AdminAppUser>(identityContext); 

     var manager = new AdminAppUserManager(userStore); 
     // Configure validation logic for usernames 
     manager.UserValidator = new UserValidator<AdminAppUser>(manager) 
     { 
      AllowOnlyAlphanumericUserNames = false, 
      RequireUniqueEmail = true 
     }; 
     // Configure validation logic for passwords 
     manager.PasswordValidator = new PasswordValidator 
     { 
      RequiredLength = 6, 
      RequireNonLetterOrDigit = true, 
      RequireDigit = true, 
      RequireLowercase = true, 
      RequireUppercase = true, 
     }; 
     var dataProtectionProvider = options.DataProtectionProvider; 
     if (dataProtectionProvider != null) 
     { 
      manager.UserTokenProvider = new DataProtectorTokenProvider<AdminAppUser>(dataProtectionProvider.Create("ASP.NET Identity")); 
     } 
     return manager; 
    } 

EDIT:

startup.auth.cs

public partial class Startup 
{ 
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 

    public static string PublicClientId { get; private set; } 

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(AdminAppIdentityDbContext.Create); 
     app.CreatePerOwinContext<AdminAppUserManager>(AdminAppUserManager.Create); 

     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Configure the application for OAuth based flow 
     PublicClientId = "self"; 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      // In production mode set AllowInsecureHttp = false 
      AllowInsecureHttp = true 
     }; 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(OAuthOptions); 

     // Uncomment the following lines to enable logging in with third party login providers 
     //app.UseMicrosoftAccountAuthentication(
     // clientId: "", 
     // clientSecret: ""); 

     //app.UseTwitterAuthentication(
     // consumerKey: "", 
     // consumerSecret: ""); 

     //app.UseFacebookAuthentication(
     // appId: "", 
     // appSecret: ""); 

     //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 
     //{ 
     // ClientId = "", 
     // ClientSecret = "" 
     //}); 
    } 
} 

startup.cs:

public partial class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     ConfigureAuth(app); 
    } 
} 

編集2:

public class AdminAppIdentityDbContext : IdentityDbContext<AdminAppUser> 
{ 
    public AdminAppIdentityDbContext() 
     : base("DefaultConnection", throwIfV1Schema: false) 
    { 
    } 

    public static AdminAppIdentityDbContext Create() 
    { 
     return new AdminAppIdentityDbContext(); 
    } 
} 

答えて

0

Owinコンテキストごとに1つのIdentityDbContextが存在することを確認するために起動時に呼び出されるConfigureAuthメソッドが必要です。その呼び出しは次のようになります。

app.CreatePerOwinContext(IdentityDbContext.Create); 

この呼び出しは、VSが自動的に生成するボイラープレートにある必要があります。あなたはまた、単に var identityContext = new AdminAppIdentityDbContext();var identityContext = context.Get<IdentityDbContext>を置き換えることができ

+0

スタートアップクラスコードを自分の編集に追加しました。その呼び出しは既にそこにある。 –

+0

AdminAppIdentityDbContext.Createはどのようなタイプの戻り値を返しますか? – DavidS

+0

'new AdminAppIdentityDbContext();' –

0

、 それは本当に問題ではありません。あなたの時間を惜しまないかもしれません。