Simple Authorization Service Provider using dependency injection unity Config
I am working on application in which i want to inject IAuthrepository in SimplerAuthorizationServiceProvider using Dependency Injection. But when i run the application it return me null exception. Here is my code.
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());
Here is 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;
}
When i run the application _repo is always null due to which it gives me null exception. Here is registering Repositories.
public static void Register(HttpConfiguration config)
var container = new UnityContainer();
container.RegisterType<IAuthRepository, AuthRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
c# asp.net-web-api asp.net-web-api2 unity-container
add a comment |
I am working on application in which i want to inject IAuthrepository in SimplerAuthorizationServiceProvider using Dependency Injection. But when i run the application it return me null exception. Here is my code.
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());
Here is 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;
}
When i run the application _repo is always null due to which it gives me null exception. Here is registering Repositories.
public static void Register(HttpConfiguration config)
var container = new UnityContainer();
container.RegisterType<IAuthRepository, AuthRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
c# asp.net-web-api asp.net-web-api2 unity-container
you try to resolve from global config but the config used to register was the one you manually created in theConfiguration
method
– Nkosi
Nov 14 '18 at 14:11
add a comment |
I am working on application in which i want to inject IAuthrepository in SimplerAuthorizationServiceProvider using Dependency Injection. But when i run the application it return me null exception. Here is my code.
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());
Here is 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;
}
When i run the application _repo is always null due to which it gives me null exception. Here is registering Repositories.
public static void Register(HttpConfiguration config)
var container = new UnityContainer();
container.RegisterType<IAuthRepository, AuthRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
c# asp.net-web-api asp.net-web-api2 unity-container
I am working on application in which i want to inject IAuthrepository in SimplerAuthorizationServiceProvider using Dependency Injection. But when i run the application it return me null exception. Here is my code.
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());
Here is 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;
}
When i run the application _repo is always null due to which it gives me null exception. Here is registering Repositories.
public static void Register(HttpConfiguration config)
var container = new UnityContainer();
container.RegisterType<IAuthRepository, AuthRepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
c# asp.net-web-api asp.net-web-api2 unity-container
c# asp.net-web-api asp.net-web-api2 unity-container
edited Nov 14 '18 at 14:17
Nkosi
115k16128193
115k16128193
asked Nov 14 '18 at 13:11
Shamshad JamalShamshad Jamal
759
759
you try to resolve from global config but the config used to register was the one you manually created in theConfiguration
method
– Nkosi
Nov 14 '18 at 14:11
add a comment |
you try to resolve from global config but the config used to register was the one you manually created in theConfiguration
method
– Nkosi
Nov 14 '18 at 14:11
you try to resolve from global config but the config used to register was the one you manually created in the
Configuration
method– Nkosi
Nov 14 '18 at 14:11
you try to resolve from global config but the config used to register was the one you manually created in the
Configuration
method– Nkosi
Nov 14 '18 at 14:11
add a comment |
1 Answer
1
active
oldest
votes
You try to resolve from static GlobalConfiguration
but the HttpConfiguration
used to register dependencies was the instance you manually created in the Configuration
method
Refactor to use the local configuration instance
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());
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301045%2fsimple-authorization-service-provider-using-dependency-injection-unity-config%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You try to resolve from static GlobalConfiguration
but the HttpConfiguration
used to register dependencies was the instance you manually created in the Configuration
method
Refactor to use the local configuration instance
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());
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
add a comment |
You try to resolve from static GlobalConfiguration
but the HttpConfiguration
used to register dependencies was the instance you manually created in the Configuration
method
Refactor to use the local configuration instance
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());
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
add a comment |
You try to resolve from static GlobalConfiguration
but the HttpConfiguration
used to register dependencies was the instance you manually created in the Configuration
method
Refactor to use the local configuration instance
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());
You try to resolve from static GlobalConfiguration
but the HttpConfiguration
used to register dependencies was the instance you manually created in the Configuration
method
Refactor to use the local configuration instance
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());
answered Nov 14 '18 at 14:14
NkosiNkosi
115k16128193
115k16128193
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
add a comment |
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
It work perfectly thanks alot you save my day
– Shamshad Jamal
Nov 14 '18 at 14:20
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53301045%2fsimple-authorization-service-provider-using-dependency-injection-unity-config%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
you try to resolve from global config but the config used to register was the one you manually created in the
Configuration
method– Nkosi
Nov 14 '18 at 14:11