使用依赖项注入统一配置的简单授权服务提供者

时间:2018-11-14 13:11:25

标签: c# asp.net-web-api asp.net-web-api2 unity-container

我正在研究要使用依赖注入在SimplerAuthorizationServiceProvider中注入IAuthrepository的应用程序。但是,当我运行该应用程序时,它会返回空异常。这是我的代码。

public void Configuration(IAppBuilder app)
{
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888

    HttpConfiguration config = new HttpConfiguration();
    UnityConfig.Register(config);
    WebApiConfig.Register(config);
    ConfigureOAuth(app);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);
}

public void ConfigureOAuth(IAppBuilder app)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/api/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider((IAuthRepository)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAuthRepository)))
    };
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}

这是SimpleAuthorizationServiceProvider类

    public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        private IAuthRepository _repo;
        public SimpleAuthorizationServerProvider(IAuthRepository repo)
        {
            _repo = repo;
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (context.ClientId == null)
            {
                context.Validated();
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
                context.Validated(identity);

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}

当我运行应用程序 _repo 时始终为null,这使它为我提供了null异常。这里正在注册存储库。

public static void Register(HttpConfiguration config)
        {
            var container = new UnityContainer();
            container.RegisterType<IAuthRepository, AuthRepository>(new HierarchicalLifetimeManager());
            config.DependencyResolver = new UnityResolver(container);
        }

1 个答案:

答案 0 :(得分:1)

您尝试从静态GlobalConfiguration解析,但是用于注册依赖项的HttpConfiguration是您在Configuration方法中手动创建的实例

重构为使用本地配置实例

public void Configuration(IAppBuilder app) {    
    HttpConfiguration config = new HttpConfiguration();
    UnityConfig.Register(config);
    WebApiConfig.Register(config);
    ConfigureOAuth(app, config.DependencyResolver);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);
}

public void ConfigureOAuth(IAppBuilder app, IDependencyResolver resolver) {
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/api/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider((IAuthRepository)resolver.GetService(typeof(IAuthRepository)))
    };
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());    
}