Exemplo n.º 1
0
        public async override Task Invoke(IOwinContext context)
        {
            if (!context.Request.Path.Equals(Path))
            {
                await Next.Invoke(context);

                return;
            }

            context.Response.OnSendingHeaders(o =>
            {
                //scope here should be already disposed
                var scopeOnHeaders   = context.GetAutofacLifetimeScope();
                var serviceOnHeaders = scopeOnHeaders.Resolve <PluggableComponent>();
                context.Response.Headers.Add("Echo", new[] { serviceOnHeaders.Echo() });
            }, this);

            //scope here should be fine
            var scope   = context.GetAutofacLifetimeScope();
            var service = scope.Resolve <PluggableComponent>();

            var responseData = new { Date = DateTime.Now, Echo = service.Echo() };

            context.Response.StatusCode  = (int)HttpStatusCode.OK;
            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(responseData));
        }
        public static ILifetimeScope GetLifetimeScopeHelper(this IOwinContext owinContext, Type type, IContainer container, bool checkForMiddleware = true)
        {
            var lifetimeScope = owinContext.GetAutofacLifetimeScope();

            if (lifetimeScope != null)
            {
                return(lifetimeScope);
            }

            var middlewareIsRegistered = owinContext.Environment.ContainsKey(CustomDisposeLifetimescopeRegisteredKey);

            if (container != null && (middlewareIsRegistered || !checkForMiddleware))
            {
                // This makes me nervous...especially because we're not disposing the lifetimeScope in the same way as https://github.com/autofac/Autofac.Owin/blob/1e6eab35b59bc3838bbd2f6c7653d41647649b01/src/Autofac.Integration.Owin/AutofacAppBuilderExtensions.cs#L414.
                lifetimeScope = container.BeginLifetimeScope(
                    MatchingScopeLifetimeTags.RequestLifetimeScopeTag,
                    b => b.RegisterInstance(owinContext).As <IOwinContext>());
                owinContext.SetAutofacLifetimeScope(lifetimeScope);
                owinContext.Set(CustomDisposeLifetimescopeKey, true);
                return(lifetimeScope);
            }

            if (container != null && !middlewareIsRegistered)
            {
                throw new ApplicationException(
                          $"Could not get autofac lifetime scope from owin context. A container was provided, " +
                          $"but cleanup middleware was not registered. " +
                          $"Be sure to call {nameof(UseIdServerAutofacIntegrationMiddleware)} in startup before {nameof(AutofacAppBuilderExtensions.UseAutofacMiddleware)}.");
            }

            throw new ApplicationException(
                      $"Could not get autofac lifetime scope from owin context when trying to resolve {type}.");
        }
Exemplo n.º 3
0
        public static ApplicationUserManager Create(
            IdentityFactoryOptions <ApplicationUserManager> options,
            IOwinContext context)
        {
            IGwintContext gwintContext = context.GetAutofacLifetimeScope().Resolve <IGwintContext>();
            var           manager      = new ApplicationUserManager(new UserStore(gwintContext));

            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                //RequireUniqueEmail = true
            };
            // Konfigurieren der Überprüfungslogik für Kennwörter.
            manager.PasswordValidator = new PasswordValidator
            {
                //RequiredLength = 6
            };
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
        /// <summary>
        /// Gets current user
        /// </summary>
        public static Task <User> GetCurrentUser(this IOwinContext owinContext)
        {
            var userId = owinContext.GetCurrentUserId();
            var scope  = owinContext.GetAutofacLifetimeScope();

            return(scope.Resolve <IRepositoryAsync <User> >().FindAsync(userId));
        }
Exemplo n.º 5
0
        public override async Task Invoke(IOwinContext context)
        {
            IAutofacDependencyManager childDependencyManager = new AutofacDependencyManager();

            childDependencyManager.UseContainer(context.GetAutofacLifetimeScope());

            context.Set <IDependencyResolver>("DependencyResolver", (IDependencyResolver)childDependencyManager);

            await Next.Invoke(context);
        }
Exemplo n.º 6
0
        public static object ResolveDependency(this IOwinContext context, Type type)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var scope = context.GetAutofacLifetimeScope();

            return(scope.ResolveOptional(type));
        }
        protected override TCultureProvider ResolveProvider(IOwinContext httpContext)
        {
            var scope = httpContext.GetAutofacLifetimeScope();

            if (scope == null)
            {
                throw new InvalidOperationException("Autofac lifetime scope is not present on the owin context.  Ensure Autofac middleware had been addeed");
            }

            return(scope.Resolve <TCultureProvider>());
        }
Exemplo n.º 8
0
        public override async Task Invoke(IOwinContext context)
        {
            if (!context.Request.Path.ToString().Contains("/favicon.ico"))
            {
                ILifetimeScope scope = context.GetAutofacLifetimeScope();
                // can use this to resolve other stuff in same lifetime scope as the owin pipeline

                _Logger.Log("Inside the 'Invoke' method of the 'LoggerMiddleware' middleware.");

                await Next.Invoke(context);
            }
        }
Exemplo n.º 9
0
        private static ILifetimeScope GetLifetimeScopeHelper(this IOwinContext owinContext, Type type)
        {
            var lifetimeScope = owinContext.GetAutofacLifetimeScope();

            if (lifetimeScope != null)
            {
                return(lifetimeScope);
            }

            throw new ApplicationException(
                      $"Could not get autofac lifetime scope from owin context when trying to resolve {type}. Did you call appBuilder.UseAutofacMiddleware() (or appBuilder.UseAutofacLifetimeScopeInjector()) before appBuilder.UseIdentityServer() in your app's startup?");
        }
        public override Task Invoke(IOwinContext context)
        {
            var lifetimeScope = context.GetAutofacLifetimeScope();

            if (lifetimeScope == null)
            {
                return(Next.Invoke(context));
            }

            var middleware = lifetimeScope.ResolveOptional <T>(TypedParameter.From(Next));

            return(middleware != null?middleware.Invoke(context) : Next.Invoke(context));
        }
Exemplo n.º 11
0
        public async override Task Invoke(IOwinContext context)
        {
            // You've access to asp.net core http context in your owin middlewares, asp.net web api odata controllers, signalr hubs, etc.

            HttpContext aspNetCoreContext = (HttpContext)context.Environment["Microsoft.AspNetCore.Http.HttpContext"];

            // do what ever you want using context.Request & context.Response

            ISomeDependency getDependencyFromAspNetCoreHttpContext = aspNetCoreContext.RequestServices.GetService <ISomeDependency>();
            ISomeDependency getDependencyFromOwinContext           = context.GetAutofacLifetimeScope().Resolve <ISomeDependency>();

            await Next.Invoke(context);
        }
        public override Task Invoke(IOwinContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            IAutofacDependencyManager childDependencyManager = new AutofacDependencyManager();

            childDependencyManager.UseContainer(context.GetAutofacLifetimeScope());

            context.Set("DependencyResolver", (IDependencyResolver)childDependencyManager);

            return(Next.Invoke(context));
        }
        private static async Task <AuthenticationTicket> GenerateAuthenticationTicket(IOwinContext context, Guid userId, string userName)
        {
            var scope = context.GetAutofacLifetimeScope();

            // identity
            var membershipService = scope.Resolve <IMembershipService>();
            var oAuthIdentity     = await membershipService.CreateIdentity(userId, OAuthDefaults.AuthenticationType).ConfigureAwait(false);

            // ticket
            var properties = new AuthenticationProperties(new Dictionary <string, string>
            {
                { "userName", userName },
                { "as:client_id", context.Get <string>("as:client_id") }
            });
            var ticket = new AuthenticationTicket(oAuthIdentity, properties);

            return(ticket);
        }
Exemplo n.º 14
0
        private async Task <User> TryGetUserWithCredentials(string username, string password, IOwinContext owinContext)
        {
            var  dbAccessor = owinContext.GetAutofacLifetimeScope().Resolve <IDbContextAccessor>();
            User user       =
                await dbAccessor
                .DbContext
                .Set <User>()
                .Where(u => u.Username == username)
                .SingleOrDefaultAsync();

            if (user != null && user.IsActive && user.VerifyPassword(password))
            {
                return(user);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Gets current user's buyer roles from claims and caches the result for short period of time
        /// </summary>
        public static IEnumerable <BuyerRole> GetCurrentUserBuyerRoles(this IOwinContext owinContext)
        {
            if (owinContext?.Authentication?.User == null ||
                owinContext.Authentication.User.Claims.IsNullOrEmpty())
            {
                return(Enumerable.Empty <BuyerRole>());
            }

            var user         = owinContext.Authentication.User;
            var scope        = owinContext.GetAutofacLifetimeScope();
            var cacheManager = scope.Resolve <ICacheManager>(TypedParameter.From(typeof(OwinContextExtensions)));

            return(cacheManager.Get($"BuyerRoles-{user.Identity.GetUserId()}", context =>
            {
                context.Monitor(scope.Resolve <IClock>().When(TimeSpan.FromMinutes(1))); // cache result for one min
                var buyerRolesJsonValue = user.Claims.Single(x => x.Type == ClaimTypes.UserData && x.ValueType == ClaimValueTypes.String).Value;
                return JsonConvert.DeserializeObject <IEnumerable <BuyerRole> >(buyerRolesJsonValue);
            }));
        }
Exemplo n.º 16
0
        private async Task<User> TryGetUserWithCredentials(string username, string password, IOwinContext owinContext)
        {
            var unitOfWork = owinContext.GetAutofacLifetimeScope().Resolve<IUnitOfWork>();
            User user =
                await unitOfWork
                .DbContext
                .Set<User>()
                .Where(u => u.Username == username)
                .SingleOrDefaultAsync();

            if (user != null && user.IsActive && user.HasPassword && user.VerifyPassword(password))
            {
                return user;
            }
            else
            {
                return null;
            }
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        public override Task Invoke(IOwinContext context)
        {
            var lifetimeScope = context.GetAutofacLifetimeScope();

            if (lifetimeScope == null)
            {
                // We pretty well protect against this, but just in case
                // someone's trying to pull a fast one...
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.LifetimeScopeNotFoundWhileInjectingMiddleware, typeof(T)));
            }

            T middleware;

            try
            {
                middleware = lifetimeScope.Resolve <T>(TypedParameter.From(this.Next));
            }
            catch (DependencyResolutionException ex)
            {
                throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, Resources.MiddlewareNotRegistered, typeof(T)), ex);
            }

            return(middleware.Invoke(context));
        }
Exemplo n.º 18
0
 public static TService ResolveKeyed <TService>([NotNull] this IOwinContext owinContext, [NotNull] object serviceKey)
 {
     return(owinContext.GetAutofacLifetimeScope().ResolveKeyed <TService>(serviceKey));
 }
Exemplo n.º 19
0
 public override Task Invoke(IOwinContext context)
 {
     LifetimeScope = context.GetAutofacLifetimeScope();
     return Next.Invoke(context);
 }
Exemplo n.º 20
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var manager = new ApplicationRoleManager(new RoleStore <ApplicationRole, string, IdentityUserRole>(context.GetAutofacLifetimeScope().Resolve <DefaultDataContext>()));

            manager.RoleValidator = new RoleValidator <ApplicationRole>(manager);
            return(manager);
        }
Exemplo n.º 21
0
 public override Task Invoke(IOwinContext context)
 {
     LifetimeScope = context.GetAutofacLifetimeScope();
     return(Next.Invoke(context));
 }
Exemplo n.º 22
0
 public static T ResolveNamed <T>(this IOwinContext context, string serviceName)
 => context.GetAutofacLifetimeScope().ResolveNamed <T>(serviceName);
Exemplo n.º 23
0
 public static T Resolve <T>(this IOwinContext context)
 => context.GetAutofacLifetimeScope().Resolve <T>();
Exemplo n.º 24
0
 /// <summary>
 /// Resolves an instance of the specified <typeparamref name="TService"/> from the current Autofac Lifetime scope container.
 /// </summary>
 /// <typeparam name="TService">The service type.</typeparam>
 /// <param name="owinContext">The owin context.</param>
 /// <returns>An instance of TService</returns>
 public static TService Resolve <TService>([NotNull] this IOwinContext owinContext)
 {
     return(owinContext.GetAutofacLifetimeScope().Resolve <TService>());
 }
Exemplo n.º 25
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>(context.GetAutofacLifetimeScope().Resolve <DefaultDataContext>()));

            // 配置用户名的验证逻辑
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                //RequireUniqueEmail = true
            };

            // 配置密码的验证逻辑
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 3,
                //RequireNonLetterOrDigit = true,
                //RequireDigit = true,
                //RequireLowercase = true,
                //RequireUppercase = true,
            };

            // 配置用户锁定默认值
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 注册双重身份验证提供程序。此应用程序使用手机和电子邮件作为接收用于验证用户的代码的一个步骤
            // 你可以编写自己的提供程序并将其插入到此处。
            manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "你的安全代码是 {0}"
            });
            manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "安全代码",
                BodyFormat = "你的安全代码是 {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Exemplo n.º 26
0
 /// <summary>
 /// Resolves an instance of the specified <typeparamref name="TService" /> from the current Autofac Lifetime scope container.
 /// </summary>
 /// <typeparam name="TService">The service type.</typeparam>
 /// <param name="owinContext">The owin context.</param>
 /// <param name="serviceName">Name of the service.</param>
 /// <returns>An instance of TService</returns>
 public static TService ResolveNamed <TService>([NotNull] this IOwinContext owinContext, [NotNull] string serviceName)
 {
     return(owinContext.GetAutofacLifetimeScope().ResolveNamed <TService>(serviceName));
 }