Asp.net web api Asp.net标识,生成WebApi令牌OAuthGrantResourceOwnerCredentialsContext-无法使用Unity访问UserManager

Asp.net web api Asp.net标识,生成WebApi令牌OAuthGrantResourceOwnerCredentialsContext-无法使用Unity访问UserManager,asp.net-web-api,unity-container,asp.net-identity,asp.net-web-api2,constructor-injection,Asp.net Web Api,Unity Container,Asp.net Identity,Asp.net Web Api2,Constructor Injection,我正在尝试设置一个项目结构,这样我就有了一个WebApi、WebUI和域层。我已将所有Asp.Net.Identity对象移动到域层,并在此处设置了ApplicationContext(从IdentityContext继承) (我使用本教程和软件包作为基础,非常好。) 在WebAPI层中,我能够正确使用帐户控制器登录和注册。但是,我无法生成访问令牌 OAuthGrantResourceOwnerCredentialsContext方法在内部使用 var userManager = context

我正在尝试设置一个项目结构,这样我就有了一个WebApi、WebUI和域层。我已将所有Asp.Net.Identity对象移动到域层,并在此处设置了ApplicationContext(从IdentityContext继承)

(我使用本教程和软件包作为基础,非常好。)

在WebAPI层中,我能够正确使用帐户控制器登录和注册。但是,我无法生成访问令牌

OAuthGrantResourceOwnerCredentialsContext方法在内部使用

var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
因此,在获取访问令牌时,似乎要使用ApplicationAuthProvider

-- 更多信息

UnityConfig.cs

container.RegisterType<ApplicationDbContext>(); //this is referencing my domain layer
container.RegisterType()//这是引用我的域层
Startup.Auth.cs

app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());

// 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),
            AllowInsecureHttp = true
        };
app.CreatePerOwinContext(()=>DependencyResolver.Current.GetService());
//为基于OAuth的流配置应用程序
PublicClientId=“self”;
OAuthOptions=新的OAuthAuthorizationServerOptions
{
TokenEndpointPath=新路径字符串(“/Token”),
Provider=新的ApplicationAuthProvider(PublicClientId),
AuthorizeEndpointPath=新路径字符串(“/api/Account/ExternalLogin”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(14),
AllowInsecureHttp=true
};
ApplicationAuthProvider.cs

已注入构造函数,如下所示

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    private ApplicationUserManager userManager;

    public ApplicationOAuthProvider(ApplicationUserManager userManager)
    {
        this.userManager = userManager;
    }

    public ApplicationOAuthProvider(string publicClientId)
    {

        //this.userManager = userManager;

        if (publicClientId == null)
        {
            throw new ArgumentNullException("publicClientId");
        }

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        //var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); //PROBLEM LINE!!!

        ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    }
}
公共类ApplicationAuthProvider:OAuthAuthorizationServerProvider
{
私有只读字符串_publicClientId;
私有应用程序管理员用户管理器;
公共ApplicationAuthProvider(ApplicationUserManager用户管理器)
{
this.userManager=userManager;
}
公共ApplicationAuthProvider(字符串publicClientId)
{
//this.userManager=userManager;
if(publicClientId==null)
{
抛出新ArgumentNullException(“publicClientId”);
}
_publicClientId=publicClientId;
}
公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
//var userManager=context.OwinContext.GetUserManager();//问题行!!!
ApplicationUser user=await userManager.FindAsync(context.UserName,context.Password);
}
}
问题行如上图所示。在请求令牌时调用此方法,并且userManager始终为null


编辑以显示UnityWebPiActivator.cs

public static class UnityWebApiActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start() 
    {
        // Use UnityHierarchicalDependencyResolver if you want to use a new child container for each IHttpController resolution.
        // var resolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
        var resolver = new UnityDependencyResolver(UnityConfig.GetConfiguredContainer());

        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}
公共静态类UnityWebPiActivator
{
///在应用程序启动时集成Unity。
公共静态void Start()
{
//如果要为每个IHttpController解析使用新的子容器,请使用UnityHierarchicalDependencyResolver。
//var resolver=新的UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
var resolver=newunitydependencysolver(UnityConfig.GetConfiguredContainer());
GlobalConfiguration.Configuration.DependencyResolver=解析程序;
}
///在应用程序关闭时处置Unity容器。
公共静态无效关机()
{
var container=UnityConfig.GetConfiguredContainer();
container.Dispose();
}
}

我刚刚创建了一个带有Identity的纯WebApi项目,检查了所有的类,不确定我是否正确理解了您的问题

标准VS2013模板在
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)
    {
        // blah - other stuff

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            Provider = new ApplicationOAuthProvider(PublicClientId),
            // another blah
        };

        app.UseOAuthBearerTokens(OAuthOptions);

        //blah-blah-blah
    }
}
我已经检查过,
applicationAuthProvider
未在其他任何地方使用。所以不需要注射

正如您所说,在这个类内部,它调用
context.OwinContext.GetUserManager()
来获取用户管理器。如果您在那里得到一个不正确的
ApplicationDbContext
实例,则将
ApplicationUserManager
的不正确实例注入Owin上下文。您是否仍有与此相关的行:

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>()

这将从Unity解析您的用户管理器,为您提供正确的
DbContext

这适用于使用Unity引导程序和IDependencyResolver的API控制器。但是,它不允许您解析OAuthProviderClass中的任何内容。仍然在寻找答案!我刚刚遇到了这一点,这似乎是可行的,但我正在努力使Unity中factorymanager的语法正确。有什么好主意吗
var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>()