Shamshad Jamal
Shamshad Jamal

Reputation: 19

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);
        }

Upvotes: 2

Views: 679

Answers (1)

Nkosi
Nkosi

Reputation: 247323

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());    
}

Upvotes: 2

Related Questions