使用依赖注入统一配置的简单授权服务提供者
Simple Authorization Service Provider using dependency injection unity Config
我正在开发我想使用依赖注入在 SimplerAuthorizationServiceProvider 中注入 IAuthrepository 的应用程序。但是当我 运行 应用程序时它 return 我空异常。这是我的代码。
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 Class
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);
}
您尝试从静态 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());
}
我正在开发我想使用依赖注入在 SimplerAuthorizationServiceProvider 中注入 IAuthrepository 的应用程序。但是当我 运行 应用程序时它 return 我空异常。这是我的代码。
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 Class
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);
}
您尝试从静态 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());
}