Exemplo n.º 1
0
        public void GetServiceReturnsNullForUnregisteredService()
        {
            var lifetimeScope   = new ContainerBuilder().Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.Null(service);
        }
        public void GetServiceReturnsNullForUnregisteredService()
        {
            var lifetimeScope   = new ContainerBuilder().Build().BeginLifetimeScope(AutofacWebApiDependencyResolver.ApiRequestTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.That(service, Is.Null);
        }
        public void GetServiceReturnsNullForUnregisteredService()
        {
            var lifetimeScope = new ContainerBuilder().Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.Null(service);
        }
        public void HandlerUpdatesDependencyScopeWithHttpRequestMessage()
        {
            var request = new HttpRequestMessage();
            var lifetimeScope = new ContainerBuilder().Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var scope = new AutofacWebApiDependencyScope(lifetimeScope);
            request.Properties.Add(HttpPropertyKeys.DependencyScope, scope);

            CurrentRequestHandler.UpdateScopeWithHttpRequestMessage(request);

            Assert.Equal(request, scope.GetService(typeof(HttpRequestMessage)));
        }
        public void GetServiceReturnsRegisteredService()
        {
            var builder = new ContainerBuilder();
            builder.Register(c => new object()).InstancePerRequest();
            var lifetimeScope = builder.Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.NotNull(service);
        }
        public void HandlerUpdatesDependencyScopeWithHttpRequestMessage()
        {
            var request       = new HttpRequestMessage();
            var lifetimeScope = new ContainerBuilder().Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var scope         = new AutofacWebApiDependencyScope(lifetimeScope);

            request.Properties.Add(HttpPropertyKeys.DependencyScope, scope);

            CurrentRequestHandler.UpdateScopeWithHttpRequestMessage(request);

            Assert.That(scope.GetService(typeof(HttpRequestMessage)), Is.EqualTo(request));
        }
Exemplo n.º 7
0
        public void GetServiceReturnsRegisteredService()
        {
            var builder = new ContainerBuilder();

            builder.Register(c => new object()).InstancePerRequest();
            var lifetimeScope   = builder.Build().BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.NotNull(service);
        }
        public void GetServiceReturnsRegisteredService()
        {
            var builder = new ContainerBuilder();

            builder.Register(c => new object()).InstancePerApiRequest();
            var lifetimeScope   = builder.Build().BeginLifetimeScope(AutofacWebApiDependencyResolver.ApiRequestTag);
            var dependencyScope = new AutofacWebApiDependencyScope(lifetimeScope);

            var service = dependencyScope.GetService(typeof(object));

            Assert.That(service, Is.Not.Null);
        }
Exemplo n.º 9
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("n");

            var dependencyScope = new AutofacWebApiDependencyScope(context.OwinContext.GetAutofacLifetimeScope());
            var authRepository  = dependencyScope.GetService(typeof(IAuthRepository)) as IAuthRepository;

            var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");

            var token = new RefreshToken()
            {
                Id         = Helper.GetHash(refreshTokenId),
                ClientId   = clientid,
                Subject    = context.Ticket.Identity.Name,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            token.ProtectedTicket = context.SerializeTicket();

            try
            {
                var result = await authRepository.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
            catch (Exception ex)
            {
                var message = ex.Message;
            }
        }
Exemplo n.º 10
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            string hashedTokenId = Helper.GetHash(context.Token);

            var dependencyScope = new AutofacWebApiDependencyScope(context.OwinContext.GetAutofacLifetimeScope());
            var authRepository  = dependencyScope.GetService(typeof(IAuthRepository)) as IAuthRepository;

            var refreshToken = await authRepository.FindRefreshToken(hashedTokenId);

            if (refreshToken != null)
            {
                //Get protectedTicket from refreshToken class
                context.DeserializeTicket(refreshToken.ProtectedTicket);
                var result = await authRepository.RemoveRefreshToken(hashedTokenId);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            if (allowedOrigin == null)
            {
                allowedOrigin = "*";
            }

            var             dependencyScope = new AutofacWebApiDependencyScope(context.OwinContext.GetAutofacLifetimeScope());
            var             authRepository  = dependencyScope.GetService(typeof(IAuthRepository)) as IAuthRepository;
            ApplicationUser user            = await authRepository.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(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrets once obtain access tokens.
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");

                return(Task.FromResult <object>(null));
            }

            var dependencyScope = new AutofacWebApiDependencyScope(context.OwinContext.GetAutofacLifetimeScope());
            var authRepository  = dependencyScope.GetService(typeof(IAuthRepository)) as IAuthRepository;

            client = authRepository.FindClient(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }