Asp.net Identity, Generate WebApi token OAuthGrantResourceOwnerCredentialsContext - no access to UserManager using Unity

瘦欲@ 提交于 2019-12-04 12:15:17

I have just create pure WebApi project with Identity, checked over the classes and not sure I understand your question correctly.

The standard VS2013 template contains this in 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
    }
}

I have checked and ApplicationOAuthProvider is not used anywhere else. So no need to inject it.

Inside of this class, as you say, it calls for context.OwinContext.GetUserManager<ApplicationUserManager>() to get user manager. If you get an incorrect instance of ApplicationDbContext there, then you inject incorrect instance of ApplicationUserManager into Owin context. Do you still have a line with this:

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

Go replace it with this:

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

This should do the job - would be the best solution.

Alternatively in ApplicationOAuthProvider replace line where you get the ApplicationUserManager from OWIN context with this:

var userManager = DependencyResolver.Current.GetService<ApplicationUserManager>()

This should resolve your user manager from Unity, giving you correct DbContext.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!