示例#1
1
        private static UserManager<IdentityUser> CreateManager(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
        {
            var userStore = new UserStore<IdentityUser>(context.Get<OAuthDbContext>());
            var manager = new UserManager<IdentityUser>(userStore);

            return manager;
        }
        public override async Task Invoke(IOwinContext context)
        {
            // Determine correlation id.
            var correlationId = context.Get<string>(OwinRequestIdKey);

            // The NuGet Gallery sends us the X-CorrelationId header.
            // If that header is present, override OWIN's owin.RequestId.
            string[] temp = null;
            if (context.Request.Headers.TryGetValue(CorrelationIdHeaderKey, out temp))
            {
                correlationId = temp[0];

                context.Set(OwinRequestIdKey, correlationId);
            }

            // As a bonus, make Serilog aware of this request ID as well.
            if (HttpContext.Current != null)
            {
                HttpContext.Current.Items[SerilogRequestIdItemName] = Guid.Parse(correlationId);
            }

            // Run all the things
            await Next.Invoke(context);

            // Set response header
            context.Response.Headers.Add("X-CorrelationId", new[] { context.Get<string>(OwinRequestIdKey) });
        }
示例#3
0
 public override Task Invoke(IOwinContext context)
 {
     if (context.Get<string>("p1") == "p1" && context.Get<int>("p2") == 2 && context.Get<object>("p3").ToString() == "p3")
     {
         return context.Response.WriteAsync("SUCCESS");
     }
     else
     {
         return context.Response.WriteAsync("FAILURE");
     }
 }
        /// <summary>
        /// Main entry point of middleware.
        /// </summary>
        /// <param name="context">Owin Context</param>
        /// <returns>Task</returns>
        public async override Task Invoke(IOwinContext context)
        {
            await Next.Invoke(context);

            var setCookie = context.Response.Headers.GetValues("Set-Cookie");
            if (setCookie != null)
            {
                var cookies = CookieParser.Parse(setCookie);

                foreach (var c in cookies)
                {
                    // Guard for stability, preventing nullref exception
                    // in case private reflection breaks.
                    if (fromHeaderProperty != null)
                    {
                        // Mark the cookie as coming from a header, to prevent
                        // System.Web from adding it again.
                        fromHeaderProperty.SetValue(c, true);
                    }

                    // HttpContext.Current turns to null in some cases after the
                    // async call to Next.Invoke() when run in a web forms
                    // application. Let's grab it from the owin environment
                    // instead.
                    var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);

                    if (httpContext != null &&
                        !httpContext.Response.Cookies.AllKeys.Contains(c.Name))
                    {
                        httpContext.Response.Cookies.Add(c);
                    }
                }
            }
        }
 public AuthenticationRepository(IOwinContext owinContext)
 {
     userManager = owinContext.GetUserManager<ApplicationUserManager>();
     roleManager = owinContext.Get<ApplicationRoleManager>();
     authenticationManager = owinContext.Authentication;
     request = owinContext.Request;
 }
 public async override Task Invoke(IOwinContext context)
 {
     context.Set(OriginalStreamKey, context.Response.Body);
     context.Response.Body = new StreamWrapper(context.Response.Body, InspectStatusCode, context);
     await Next.Invoke(context);
     
     StatusCodeAction action;
     string link;
     int statusCode = context.Response.StatusCode;
     bool? replace = context.Get<bool?>(ReplacementKey);
     if (!replace.HasValue)
     {
         // Never evaluated, no response sent yet.
         if (options.StatusCodeActions.TryGetValue(statusCode, out action)
             && links.TryGetValue(statusCode, out link)
             && action != StatusCodeAction.Ignore)
         {
             await SendKitten(context, link);
         }
     }
     else if (replace.Value == true)
     {
         if (links.TryGetValue(statusCode, out link))
         {
             await SendKitten(context, link);
         }
     }
 }
 public override Task Invoke(IOwinContext context)
 {
     String path = context.Get<String>("owin.RequestPath");
     if (rewriteDict.ContainsKey(path))
         context.Set<String>("owin.RequestPath", rewriteDict[path]);
     return Next.Invoke(context);
 }
示例#8
0
 public PaymentService(IUserService userService, IEmailService emailService)
 {
     _emailService = emailService;
     _userService = userService;
     _owin = HttpContext.Current.GetOwinContext();
     _dbContext = _owin.Get<ApplicationDbContext>();
 }
        public static CategoryManager Create(IdentityFactoryOptions<CategoryManager> options, IOwinContext context)
        {
            ICategoryDataAccess categoryData = context.Get<SqlConnection>().As<ICategoryDataAccess>();
            CategoryManager manager = new CategoryManager(categoryData);

            return manager;
        }
示例#10
0
 private void PrintCurrentIntegratedPipelineStage(IOwinContext context, string msg)
 {
     var currentIntegratedpipelineStage = HttpContext.Current.CurrentNotification;
     context.Get<TextWriter>("host.TraceOutput").WriteLine(
         "Current IIS event: " + currentIntegratedpipelineStage
         + " Msg: " + msg);
 }
示例#11
0
        public override Task Invoke(IOwinContext context)
        {
            var rep = context.Response;
            rep.StatusCode = 404;

            //判断调用次数,避免无限递归
            var invokeTimes = context.Get<Int32>(INVOKE_TIMES);
            invokeTimes++;
            if (invokeTimes > 1 || String.IsNullOrEmpty(RewritePath))
            {
                String msg = "404 Not Found";
                rep.ContentLength = msg.Length;
                return rep.WriteAsync(msg);
            }
            context.Set(INVOKE_TIMES, invokeTimes);

            context.Set<String>("owin.RequestPath", RewritePath);
            OwinMiddleware first = server.GetFirstMiddlewareInstance();
            if (first == null)
                throw new ArgumentException($"Middleware '{this.GetType().FullName};{this.GetType().Assembly.GetName().Name}' must not be the first middleware,and recommand to be set to the last one.");

            //清理OwinContext
            foreach (var cleaner in server.GetMiddlewares<IOwinContextCleaner>())
                cleaner.Clean(context);

            return first.Invoke(context);
        }
示例#12
0
        // callback function for IAppBuilder.CreatePerOwinContext
        public static AccountManager Create(IdentityFactoryOptions<AccountManager> options, IOwinContext context)
        {
            IAccountDataAccess accountData = context.Get<SqlConnection>().As<IAccountDataAccess>();
            AccountManager manager = new AccountManager(accountData);

            return manager;
        }
 public string Service(IOwinContext context, IDictionary<string, object> data)
 {
     var rep = context.Response;
     context.GetSession().Clear();
     rep.Redirect(context.Get<String>("ContextPath"));
     return null;
 }
        public static UserManagerFactory Create(IdentityFactoryOptions<UserManagerFactory> options,
            IOwinContext context)
        {
            var manager = new UserManagerFactory(new UserStore(context.Get<WealthEconomyContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<User, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            // TODO Review this!
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                //RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                //RequireUppercase = true,
            };

            manager.EmailService = new EmailService();
            manager.ConfirmEmailUrl = string.Format("{0}/account/confirmEmail", AppSettings.ClientAppUrl);

            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<User, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }

            return manager;
        }
示例#15
0
        public Task Invoke(IOwinContext context, Func<Task> next)
        {
            var request = context.Request;
            if (request.Method != "GET" || !_path.IsWildcardMatch(request.Path))
                return next.Invoke();

            var environment = request.Query["environment"];
            var machine = request.Query["machine"];
            var application = request.Query["application"];
            var instance = request.Query["instance"];

            if (string.IsNullOrWhiteSpace(machine))
                throw new HttpException((int)HttpStatusCode.BadRequest, "Machine parameter is required");

            if (string.IsNullOrWhiteSpace(application))
                throw new HttpException((int)HttpStatusCode.BadRequest, "Application parameter is required");

            try
            {
                var clientCredentials = context.Get<IClientCredentials>("ClientCredentials");

                var config = _ruleData.TraceConfig(clientCredentials, environment, machine, application, instance);

                context.Response.ContentType = "application/json";
                return context.Response.WriteAsync(config.ToString(Formatting.Indented));
            }
            catch (Exception ex)
            {
                if (ex is HttpException) throw;
                throw new HttpException((int)HttpStatusCode.InternalServerError, ex.Message, ex);
            }
        }
        public override Task Invoke(IOwinContext context)
        {
            validateStage(context, expectedStageName, middlewareId);
            context.Get<Stack<int>>("stack").Push(middlewareId);

            return this.Next.Invoke(context).ContinueWith((result) =>
            {
                validateStage(context, RequestNotification.EndRequest, middlewareId);

                var expectedMiddlewareId = context.Get<Stack<int>>("stack").Pop();
                if (expectedMiddlewareId != middlewareId)
                {
                    throw new Exception(string.Format(Error_Incorrect_Middleware_Unwinding, expectedMiddlewareId, middlewareId));
                }
            });
        }
        public static ApplicationUserManager CreateApplicationUserManager(
            IdentityFactoryOptions<ApplicationUserManager> options,
            IOwinContext context)
        {
            var manager =
                new ApplicationUserManager(
                    new ApplicationUserStore(context.Get<UrfIdentityDataContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser, Guid>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 8,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application
            // uses Phone and Emails as a step of receiving a code for
            // verifying the user You can write your own provider and plug it
            // in here.
            manager.RegisterTwoFactorProvider(
                "SMS Code", new PhoneNumberTokenProvider<ApplicationUser, Guid>
                {
                    MessageFormat = AccountResources.OAuth_SMS_Body
                });

            manager.RegisterTwoFactorProvider(
                "Email Code", new EmailTokenProvider<ApplicationUser, Guid>
                {
                    Subject = AccountResources.OAuth_Email_Subject,
                    BodyFormat = AccountResources.OAuth_Email_Body
                });

            manager.SmsService = new SmsMessagingService();
            manager.EmailService = new EmailMessagingService();

            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser, Guid>(
                        dataProtectionProvider.Create("UrfIdentity"));
            }
            return manager;
        }
        public override async Task Invoke(IOwinContext context)
        {
            var operationId = context.Get<string>(Consts.OperationIdContextKey);
            if(operationId != null)
                OperationIdContext.Set(operationId);

            await Next.Invoke(context);
        }
 private void validateStage(IOwinContext context, RequestNotification expectedStageName, int middlewareId)
 {
     var calledAtStage = context.Get<System.Web.HttpContextWrapper>("System.Web.HttpContextBase").CurrentNotification;
     if (calledAtStage != expectedStageName)
     {
         throw new Exception(string.Format(Error_UnexpectedMiddleware, expectedStageName, calledAtStage, middlewareId));
     }
 }
        public override Task Invoke(IOwinContext context)
        {
            String path = context.Get<String>("owin.RequestPath");
            if (!route.IsMatch(path))
                return InvokeNotMatch(context);

            //如果还没有解析插件名称和路径
            if (context.Get<String>(QOMVC_PLUGIN_KEY) == null)
            {
                var groups = route.Match(path).Groups;
                var dic = route.GetGroupNames().ToDictionary(name => name, name => groups[name].Value);
                foreach (var key in dic.Keys.Where(t => t != "0"))
                    context.Environment.Add(key, dic[key]);
            }
            //交给派生的Middleware
            return Invoke(context, context.Get<String>(QOMVC_PLUGIN_KEY), context.Get<String>(QOMVC_PATH_KEY));
        }
 private Task SendKitten(IOwinContext context, string link)
 {
     context.Response.Body = context.Get<Stream>(OriginalStreamKey);
     context.Response.ContentType = "text/html";
     string body = string.Format("<html><body><img src=\"{0}\" /></body></html>", 
         HttpUtility.HtmlEncode(link));
     context.Response.ContentLength = body.Length;
     return context.Response.WriteAsync(body);
 }
        private static Guid GetAnonymousUserId()
        {
            IOwinContext owinContext = HttpContext.Current?.GetOwinContext();
            string       anonymousId = owinContext?.Get <string>(OwinConstants.AnonymousId);

            return(string.IsNullOrEmpty(anonymousId)
                ? Guid.NewGuid()
                : new Guid(anonymousId));
        }
        public async Task WriteResponseAsync(IOwinContext context, Exception e, FrameworkLogger logger)
        {
            logger.LogError("Internal server error", e);

            await WriteResponseAsync(context, HttpStatusCode.InternalServerError, JObject.FromObject(new
            {
                error = "Internal server error",
                httpRequestId = context.Get<string>(CorrelationIdMiddleware.CorrelationIdHeaderKey)
            }));
        }
        public override Task Invoke(IOwinContext context)
        {
            OperationIdFromEnvironment = context.Get<string>(Consts.OperationIdContextKey);
            OperationIdFromAmbientContext = OperationIdContext.Get();

            if(Next == null)
                return Task.FromResult<object>(null);

            return Next.Invoke(context);
        }
        //public CloudStorageMananger() {
        //    providers = new Dictionary<string, ICloudStorageProvider>();
        //    providers.Add("azure", new AzureCloudStorageProvider(context)); // como definir y crear el CloudStorageAccount por defecto
        //    providers.Add("rackspace", new RackspaceCloudStorageProvider());
        //    providers.Add("amazon", new AmazonCloudStorageProvider());
        //}
        //public CloudStorageMananger(ApplicationDbContext context) {
        public CloudStorageMananger(IOwinContext context)
        {
            providers = new Dictionary<string, ICloudStorageProvider>();

            var dbContext = context.Get<ApplicationDbContext>(); // cuidado aquí solo sirve con ese namespace y no se pueden mezclar.

            providers.Add("azure", new AzureCloudStorageProvider(dbContext)); // como definir y crear el CloudStorageAccount por defecto
            providers.Add("rackspace", new RackspaceCloudStorageProvider());
            providers.Add("amazon", new AmazonCloudStorageProvider());
        }
        public string GetRequestCookie(IOwinContext context, string key)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var webContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            var cookie = webContext.Request.Cookies[key];
            return cookie == null ? null : cookie.Value;
        }
 public override Task Invoke(IOwinContext context)
 {
     String path = context.Get<String>("owin.RequestPath");
     if (redirectDict.ContainsKey(path))
     {
         context.Response.Redirect(redirectDict[path]);
         context.Response.ContentLength = 0;
         return context.Response.WriteAsync(String.Empty);
     }
     return Next.Invoke(context);
 }
        // See http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/
        public static ApplicationRoleManager CreateApplicationRoleManager(
            IdentityFactoryOptions<ApplicationRoleManager> options,
            IOwinContext context)
        {
            var appRoleManager =
                new ApplicationRoleManager(
                    new ApplicationRoleStore(
                        context.Get<UrfIdentityDataContext>()));

            return appRoleManager;
        }
        public async override Task Invoke(IOwinContext context)
        {
            var start = DateTime.Now;
            var requestId = context.Get<string>("custom:requestId");

            await this.Next.Invoke(context);

            var end = DateTime.Now;

            var duration = end - start;
            
            Debug.WriteLine($"{requestId} - {context.Request.Method} {context.Request.Uri} process in {duration.TotalMilliseconds} ms");
        }
示例#30
0
文件: Program.cs 项目: Indifer/Test
        // Run once per request
        private Task UpgradeToWebSockets(IOwinContext context, Func<Task> next)
        {
            WebSocketAccept accept = context.Get<WebSocketAccept>("websocket.Accept");
            if (accept == null)
            {
                // Not a websocket request
                return next();
            }

            accept(null, WebSocketEcho);

            return Task.FromResult<object>(null);
        }
 public async override Task Invoke(IOwinContext context)
 {
     if (context.Authentication.User != null && !String.IsNullOrWhiteSpace(context.Authentication.User.Identity.Name) && context.Authentication.User.Identity.IsAuthenticated)
     {
         IDependencyScope Scope = context.Get<IDependencyScope>();
         ClientUserManager UserManager = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
         var userClient = await UserManager.FindByEmailAsync(context.Authentication.User.Identity.Name);
         if (userClient.Locale != null && !string.IsNullOrEmpty(userClient.Locale))
         {
             Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(userClient.Locale);
         }
     }
     await Next.Invoke(context);
 }
        private void logDebugMessage(IOwinContext context, string msg)
        {
            var currentStage = HttpContext.Current.CurrentNotification;

            context.Get <TextWriter>("host.TraceOutput").WriteLine("Owin CSP Nonce Debug Stage: " + currentStage + " Msg: " + msg);
        }
示例#33
0
 // Methods
 public static ApplicationPermissionManager Create(IdentityFactoryOptions <ApplicationPermissionManager> options, IOwinContext context)
 {
     return(new ApplicationPermissionManager(context.Get <ApplicationDbContext>()));
 }
示例#34
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var manager = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context.Get <CoreDbContext>()));

            return(manager);
        }
 public static AppDbContext Create(IdentityFactoryOptions <AppDbContext> options, IOwinContext context)
 {
     return(new AppDbContext(context.Get <DbRepositoryArgs>().ConnectionNameOrConnectionString));
 }
示例#36
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <User, Role, int, UserLogin, UserRole, UserClaim>(context.Get <UserContext>()));

            // Настройка логики проверки имен пользователей
            manager.UserValidator = new UserValidator <User, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Настройка логики проверки паролей
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Настройка параметров блокировки по умолчанию
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Регистрация поставщиков двухфакторной проверки подлинности. Для получения кода проверки пользователя в данном приложении используется телефон и сообщения электронной почты
            // Здесь можно указать собственный поставщик и подключить его.
            manager.RegisterTwoFactorProvider("Код, полученный по телефону", new PhoneNumberTokenProvider <User, int>
            {
                MessageFormat = "Ваш код безопасности: {0}"
            });
            manager.RegisterTwoFactorProvider("Код из сообщения", new EmailTokenProvider <User, int>
            {
                Subject    = "Код безопасности",
                BodyFormat = "Ваш код безопасности: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <User, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
示例#37
0
        public static ApplicationRoleManager CreateForOwin(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var db = context?.Get <EFDbContext>();

            return(CreateForEF(db));
        }
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var roleStore = new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>());

            return(new ApplicationRoleManager(roleStore));
        }
示例#39
0
 public static ApplicationRoleManagerMongo Create <T>(IdentityFactoryOptions <ApplicationRoleManagerMongo> options, IOwinContext context) where T : DbContext
 {
     return(new ApplicationRoleManagerMongo(new RoleStore <IdentityRole>(context.Get <T>())));
 }
示例#40
0
 public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
 {
     return(new ApplicationRoleManager(new RoleStore <IdentityRole>(context.Get <SociosBD>())));
 }
示例#41
0
        private void PrintCurrentIntegratedPipelineStage(IOwinContext context, string msg)
        {
            var currentIntegratedpipelineStage = HttpContext.Current.CurrentNotification;

            context.Get <TextWriter>("host.TraceOutput").WriteLine("Current IIS event: " + currentIntegratedpipelineStage + " Msg: " + msg);
        }
示例#42
0
 public AccountController(IOwinContext owinContext, IUserActionService actionService)
 {
     _userManager   = owinContext.GetUserManager <ApplicationUserManager>();
     _signInManager = owinContext.Get <ApplicationSignInManager>();
     _actionService = actionService;
 }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager     = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>()));

            var roleAdministrador  = "Administrador";
            var senhaAdministrador = "Admin@123";

            var roleUsuario  = "Usuário";
            var senhaUsuario = "User@123";


            if (!roleManager.RoleExists(roleAdministrador))
            {
                roleManager.Create(new IdentityRole(roleAdministrador));
            }

            if (!roleManager.RoleExists(roleUsuario))
            {
                roleManager.Create(new IdentityRole(roleUsuario));
            }

            var usuarioAdministrador = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var usuario = new ApplicationUser
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };


            if (manager.Create(usuarioAdministrador, senhaAdministrador).Succeeded)
            {
                manager.AddToRole(usuarioAdministrador.Id, roleAdministrador);
            }

            if (manager.Create(usuario, senhaUsuario).Succeeded)
            {
                manager.AddToRole(usuario.Id, roleUsuario);
            }


            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {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);
        }
示例#44
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager          = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));
            var identitySettings = new IdentitySettings();

            //TODO: Implement reading these identity setting from a store.

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = identitySettings.AllowOnlyAlphanumericUserNames,
                RequireUniqueEmail             = identitySettings.RequireUniqueEmail
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = identitySettings.MinimumPasswordLength,
                RequireNonLetterOrDigit = identitySettings.RequireNonLetterOrDigit,
                RequireDigit            = identitySettings.RequireDigit,
                RequireLowercase        = identitySettings.RequireLowercase,
                RequireUppercase        = identitySettings.RequireUppercase,
            };
            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = identitySettings.UserLockoutEnabledByDefault;
            manager.DefaultAccountLockoutTimeSpan        = identitySettings.DefaultAccountLockoutTimeSpan;
            manager.MaxFailedAccessAttemptsBeforeLockout = identitySettings.MaxFailedAccessAttemptsBeforeLockout;
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug in here.
            manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "SecurityCode",
                BodyFormat = "Your security code is {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);
        }
示例#45
0
 public static ApplicationRolePermissionManager Create(IdentityFactoryOptions <ApplicationRolePermissionManager> options, IOwinContext context)
 {
     return(new ApplicationRolePermissionManager(
                new InspurRoleStore(context.Get <ApplicationDbContext>()),
                new InspurRolePermissionStore <InspurUser>(context.Get <ApplicationDbContext>())));
 }
示例#46
0
        public static MyUserManager Create(IdentityFactoryOptions <MyUserManager> options, IOwinContext context)
        {
            var manager = new MyUserManager(new UserStore <User, MyRole, long, MyLogin, MyUserRole, MyClaim>(context.Get <XContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <MyUser, long>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug in here.
            manager.RegisterTwoFactorProvider(
                "PhoneCode",
                new PhoneNumberTokenProvider <User, long>
            {
                MessageFormat = "Your security code is: {0}"
            });
            manager.RegisterTwoFactorProvider(
                "EmailCode",
                new EmailTokenProvider <User, long>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is: {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <MyUser, long>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
示例#47
0
 public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
 {
     return(new ApplicationRoleManager(new ApplicationSignInManager.ApplicationRoleStore(context.Get <DbContext>())));
 }
示例#48
0
        public static AppRoleManager Create(IdentityFactoryOptions <AppRoleManager> options, IOwinContext context)
        {
            var db = context.Get <ApplicationDbContext>();

            return(new AppRoleManager(new RoleStore <ApplicationRole>(db)));
        }
示例#49
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var userStore = new UserStore <ApplicationUser>((IdentityDbContext <ApplicationUser>)context.Get <IDbContext>());
            var manager   = new ApplicationUserManager(userStore);

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };
            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });


            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
示例#50
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new FrontUserStore <ApplicationUser>(context.Get <ApplicationDbContext>() as SQLDatabase));

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

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

            // 配置用户锁定默认值
            manager.UserLockoutEnabledByDefault          = false;
            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);
        }
示例#51
0
 public static AppRoleManager Create(IdentityFactoryOptions <AppRoleManager> options, IOwinContext context)
 {
     return(new AppRoleManager(new RoleStore <AppRole>(context.Get <AppDbContext>())));
 }
 public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager>oprions,
      IOwinContext owinContext)
 {
      ShopDBContext context = owinContext.Get<ShopDBContext>();
      return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
 }
示例#53
0
        // Methods
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            #region Contracts

            if (options == null)
            {
                throw new ArgumentNullException();
            }
            if (context == null)
            {
                throw new ArgumentNullException();
            }

            #endregion

            // 建立使用者管理員
            var userManager = new ApplicationUserManager(context.Get <ApplicationDbContext>());
            if (userManager == null)
            {
                throw new InvalidOperationException();
            }

            // 設定使用者名稱的驗證邏輯
            userManager.UserValidator = new UserValidator <ApplicationUser>(userManager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // 設定密碼的驗證邏輯
            userManager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 5,     // 最小長度
                RequireNonLetterOrDigit = false, // 是否需要一個非字母或是數字
                RequireDigit            = false, // 是否需要一個數字
                RequireLowercase        = false, // 是否需要一個小寫字母
                RequireUppercase        = false, // 是否需要一個大寫字母
            };

            // 設定使用者鎖定詳細資料
            userManager.UserLockoutEnabledByDefault          = true;
            userManager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            userManager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 註冊雙因素驗證提供者。此應用程式使用手機和電子郵件接收驗證碼以驗證使用者
            // 您可以撰寫專屬提供者,並將它外掛到這裡。
            userManager.RegisterTwoFactorProvider("電話代碼", new PhoneNumberTokenProvider <ApplicationUser>
            {
                MessageFormat = "您的安全碼為 {0}"
            });
            userManager.RegisterTwoFactorProvider("電子郵件代碼", new EmailTokenProvider <ApplicationUser>
            {
                Subject    = "安全碼",
                BodyFormat = "您的安全碼為 {0}"
            });
            userManager.EmailService = new EmailService();
            userManager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }

            // 回傳
            return(userManager);
        }
示例#54
0
 public static string GetRequestId(this IOwinContext self)
 {
     return(self.Get <string>(Constants.RequestIdOwinEnvironmentKey));
 }
示例#55
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(context.Get <ApplicationDbContext>()));

            manager.UserValidator = new UserValidator <ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
 public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> option, IOwinContext owinContext)
 {
     return(new ApplicationUserManager(new ApplicationUserStore(owinContext.Get <ApplicationDbContext>())));
 }
示例#57
0
        public static ApplicationRoleManager Create(IOwinContext context)
        {
            var store = new RoleStore <IdentityRole>(context.Get <ApplicationDbContext>());

            return(new ApplicationRoleManager(store));
        }
示例#58
0
        public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
        {
            var appRoleManager = new ApplicationRoleManager(new RoleStore <IdentityRole>(context.Get <EntityConnection>()));

            return(appRoleManager);
        }
示例#59
0
 public TransportCardRoleStore(IOwinContext context)
 {
     _db = context.Get <QLessEntities>();
 }
示例#60
0
 public static ApplicationRoleManager Create(IdentityFactoryOptions <ApplicationRoleManager> options, IOwinContext context)
 {
     return(new ApplicationRoleManager(new RoleStore <ApplicationRole, int, ApplicationUserRole>(context.Get <GovHistoryDbContext>())));
 }