Asp.net-Identity

自定義 UserManager 在 OAuthAuthorizationServerProvider 中不可用

  • October 16, 2015

我在 WebApi 系統中實現 ASP.Net Identity 2。要管理新帳戶的電子郵件確認,我必須創建一個自定義ApplicationUserManager並註冊它,以便為每個請求創建它:

public class IdentityConfig{
   public static void Initialize(IAppBuilder app)
   {
       [snip]
       app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
   }

它在 ApiController 中正常工作,如下所示:

public class AccountController : ApiController
{
   public ApplicationUserManager UserManager
   {
       get
       {
           return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
       }
   }

我面臨的問題是ApplicationUserManager.Create在我嘗試在 OAuth 令牌創建方法中訪問它之前沒有呼叫該方法:

public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
   public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
   {
       var mgr = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

在上面的程式碼中,mgr 為 null,因為 GetUserManager 檢索到 null

令牌創建方法是否在管道中以某種方式更早,以便CreatePerOwinContext尚未呼叫這些方法?如果是這樣,記憶體 anApplicationUserManager以便在內部使用的最佳方法是GrantResourceOwnerCredentials什麼?

這個很棘手。事實證明,啟動程式碼必須按一定的順序完成。

此程式碼將起作用。

public class IdentityConfig{
   public static void Initialize(IAppBuilder app)
   {   
       // correct... first create DB context, then user manager, then register  OAuth Provider
       app.CreatePerOwinContext(AuthContext.Create);
       app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

       OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
       {
           AllowInsecureHttp = true,
           TokenEndpointPath = new PathString("/token"),
           AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
           Provider = new SimpleAuthorizationServerProvider()
       };
       app.UseOAuthAuthorizationServer(OAuthServerOptions);
       app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
   }
}

如果您更改向應用程序註冊程式碼的順序,您可能會得到意想不到的後果。此程式碼導致 ApplicationUserManager 在令牌生成方法 GrantResourceOwnerCredentials 中為空

// wrong... these two lines must be after the ApplicationUserManager.Create line
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

[snip]

app.CreatePerOwinContext(AuthContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

當我在做這件事時,還有另一件事可能會絆倒某人。這些行導致 AuthContext 在令牌生成方法 GrantResourceOwnerCredentials 中為空

// wrong... The AuthContext must be instantiated before the ApplicationUserManager
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext(AuthContext.Create);

[snip]

app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

引用自:https://stackoverflow.com/questions/27731893