예제 #1
0
 public RolesAndUsersHelper(ApplicationDbContext db)
 {
     context     = db;
     userManager = OwinContextExtensions.GetUserManager <ApplicationUserManager>(HttpContext.Current.GetOwinContext());
     roleManager = new RoleManager <IdentityRole>(
         new RoleStore <IdentityRole>(context));
 }
예제 #2
0
        public static TService Resolve <TService>()
        {
            IOwinContext context = HttpContext.Current.GetOwinContext();
            var          autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context);

            return(autofacLifetimeScope.Resolve <TService>());
        }
예제 #3
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <User>(OwinContextExtensions.Get <SportsEventsDbContext>(context)));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <User>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };
            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = false,
                RequireLowercase        = false,
                RequireUppercase        = false,
            };
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = new DataProtectorTokenProvider <User>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
예제 #4
0
        public static TService Resolve <TService>(IOwinContext context)
        {
            // autofacLifetimeScope is 'AutofacWebRequest'
            // visit http://stackoverflow.com/questions/25871392/autofac-dependency-injection-in-implementation-of-oauthauthorizationserverprovid
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context);

            return(autofacLifetimeScope.Resolve <TService>());
        }
예제 #5
0
 /// <summary>
 /// Resolve with autofac, or if autofac doesn't exist in the owin context for whatever reason use the provided instance.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="factory"></param>
 /// <param name="instance"></param>
 public static void RegisterAsAutofacResolvableOrUse <T>(this IdentityServerServiceFactory factory, T instance, RegistrationContext context = null) where T : class
 {
     factory.RegisterAsAutofacResolvable <T>(resolveWithOwinContextFunc:
                                             owinContext =>
     {
         var autofac = OwinContextExtensions.GetAutofacLifetimeScope(owinContext);
         return(autofac != null
                 ? autofac.Resolve <T>()
                 : instance);
     },
                                             context: context);
 }
예제 #6
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var lifetimeScope    = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var queryProcessor   = lifetimeScope.Resolve <QueryProcessor>();
            var commandProcessor = lifetimeScope.Resolve <CommandProcessor>();
            await Task.CompletedTask;

            var loginCommand = new LoginEmployeeCommand(context.UserName, context.Password);
            var loginResult  = commandProcessor.Handle(loginCommand);
            var identity     = new ClaimsIdentity(context.Options.AuthenticationType);

            if (loginResult.Success)
            {
                identity.AddClaim(new Claim(ClaimTypes.Name, loginResult.Result.Name));
                identity.AddClaim(new Claim(ClaimTypes.Role, loginResult.Result.EmployeeGroupId.ToString()));
                identity.AddClaim(new Claim("EmployerId", loginResult.Result.EmployerId.ToString()));

                context.Validated(identity);
            }
            else
            {
                context.SetError("invalid_grant", "Provided username and password are incorrect");
                return;
            }



            //if (context.UserName == "admin" && context.Password == "admin")
            //{
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "admin2"));
            //    identity.AddClaim(new Claim("username", "admin"));
            //    identity.AddClaim(new Claim(ClaimTypes.Name, "Sourav Mondal"));

            //}
            //else if (context.UserName == "user" && context.Password == "user")
            //{
            //    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            //    identity.AddClaim(new Claim("username", "user"));
            //    identity.AddClaim(new Claim(ClaimTypes.Name, "Suresh Sha"));
            //    context.Validated(identity);
            //}
            //else
            //{
            //    context.SetError("invalid_grant", "Provided username and password is incorrect");
            //    return;
            //}
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new UserStore <ApplicationUser>(OwinContextExtensions.Get <ApplicationDbContext>(context)));

            // 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);
        }
        public async Task <JsonResult <string> > Authorized()
        {
            //Retrieve AuthorizeService
            authorizatonService = OwinContextExtensions.GetAuthorizationService(HttpContext.Current.GetOwinContext());

            //simulate retreive employee from datastore
            var employee = new Employee {
                Id = 5, Name = "Stijn Peeters"
            };

            if (!(await authorizatonService.AuthorizeAsync((ClaimsPrincipal)User, employee, ExampleConstants.EmployeeDataAccessPolicy)))
            {
                return(Json("You are not authorized!"));
            }
            return(Json("You are authorized!"));
        }
예제 #9
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

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

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

            var  autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var  userManager          = autofacLifetimeScope.Resolve <ApplicationUserManager>();
            User user = await userManager.FindAsync(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));
            foreach (var role in user.Roles)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, role));
            }
            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
                },
                {
                    "isAdmin", user.Roles.Any(t => t == "Administrator").ToString()
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
예제 #10
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            var lifetimeScope  = OwinContextExtensions.GetAutofacLifetimeScope(HttpContext.Current.GetOwinContext());
            var queryProcessor = lifetimeScope.Resolve <QueryProcessor>();

            var principal       = actionContext.RequestContext.Principal as ClaimsPrincipal;
            var employeeGroupId = principal
                                  .Claims
                                  .Where(c => c.Type == ClaimTypes.Role)
                                  .Select(c => c.Value)
                                  .DefaultIfEmpty("0")
                                  .FirstOrDefault()
                                  .ToInt();

            queryProcessor.Handle(new HasEmployeeGroupPermissionQuery(employeeGroupId, _permission));

            return(base.IsAuthorized(actionContext));
        }
예제 #11
0
        private async Task <ClaimsIdentity> CreateIdentity()
        {
            ClaimsIdentity identity = null;

            //用户
            var user = new IotUser();

            user.Id       = Guid.NewGuid().ToString();
            user.UserName = "******";
            user.NickName = "农业气象物联网";

            //Context
            var owinContext = HttpContext.GetOwinContext();
            var userManager = OwinContextExtensions.GetUserManager <UserManager <IotUser, string> >(owinContext);

            identity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            return(identity);
        }
예제 #12
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // get ther current lifetimescope from the requqest
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var userManager          = autofacLifetimeScope.Resolve <ClientPortalUserManager>();
            ClientPortalUser user    = await userManager.FindByNameAsync(context.UserName);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (await userManager.IsLockedOutAsync(user.Id) || user.IsApproved == false)
            {
                context.SetError("invalid_grant", "The user is locked out.");
                return;
            }

            if (!await userManager.CheckPasswordAsync(user, context.Password))
            {
                await userManager.AccessFailedAsync(user.Id);

                if (await userManager.IsLockedOutAsync(user.Id))
                {
                    context.SetError("invalid_grant", "The user is locked out.");
                    return;
                }
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            await userManager.ResetAccessFailedCountAsync(user.Id);

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);

            context.Validated(ticket);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            var auth = autofacLifetimeScope.Resolve <IAuthenticationService>();

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

            var user = await auth.SignIn(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);
        }
예제 #14
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var autofacLifetimeScope = OwinContextExtensions.GetAutofacLifetimeScope(context.OwinContext);
            //var AuthenticationService = autofacLifetimeScope.Resolve<IAuthenticationService>();

            //var AuthenticationService = test.Resolve<IAuthenticationService>();

            IAuthenticationService AService = new AuthenticationService();

            if (AService != null)
            {
                var Resp = AService.AuthenticateUser(new AuthenticationDTO()
                {
                    UserName = context.UserName, Password = context.Password
                });

                if (Resp == null || Resp.Result == null || Resp.Status == false || Resp.ResposeID != 0)
                {
                    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));

                if (Resp.Result.Roles != null)
                {
                    foreach (var Role in Resp.Result.Roles)
                    {
                        identity.AddClaim(new Claim("role", Role));
                    }
                }

                context.Validated(identity);
            }
        }
예제 #15
0
        public void GetAutofacLifetimeScopeThrowsWhenProvidedNullInstance()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => OwinContextExtensions.GetAutofacLifetimeScope(null));

            Assert.Equal("context", exception.ParamName);
        }
예제 #16
0
        public IHttpActionResult Get()
        {
            var userId = OwinContextExtensions.GetUserId(HttpContext.Current.GetOwinContext());

            return(Ok(Order.CreateOrders()));
        }
        public void SetAutofacLifetimeScopeThrowsWhenProvidedNullContextInstance()
        {
            var exception = Assert.Throws <ArgumentNullException>(() => OwinContextExtensions.SetAutofacLifetimeScope(null, new Mock <ILifetimeScope>().Object));

            Assert.Equal("context", exception.ParamName);
        }
예제 #18
0
 public UserRoleRepository(ApplicationDbContext dbContext)
 {
     DbContext = dbContext;
     UserManager = OwinContextExtensions.GetUserManager<ApplicationUserManager>(HttpContext.Current.GetOwinContext());
     UserRepository = new UserRepository(dbContext);
 }
예제 #19
0
 public static ApplicationSignInManager Create(
     IdentityFactoryOptions <ApplicationSignInManager> options,
     IOwinContext context)
 {
     return(new ApplicationSignInManager((ApplicationUserManager)OwinContextExtensions.GetUserManager <ApplicationUserManager>(context), context.get_Authentication()));
 }
예제 #20
0
        public static void Init(
            Func <string, string> getConfig,
            Type E,
            Func <string, object> getSession,
            Action <string, object> setSession,
            Func <IOwinContext> getContext)
        {
            G.GetSetting = getConfig;
            G.GetContext = getContext;
            var eProperty = E.GetProperties();

            //G.UserManager = () => OwinContextExtensions.Get<ApplicationUserManager>(getContext());
            //G.SignManager = () => OwinContextExtensions.Get<ApplicationSignInManager>(getContext());
            G.RoleManager = () => OwinContextExtensions.Get <ApplicationRoleManager>(getContext());
            Action <PropertyInfo> setValue = p =>
            {
                var value = G.GetSetting(p.Name);
                if (value == null)
                {
                    return;
                }
                if (value.Text() == "")
                {
                    return;
                }
                p.SetValue(null, value.MyTryConvert(p.PropertyType));
            };

            typeof(G).GetProperties().Where(b => b.GetObjectCustomAttribute <ConfigAttribute>() != null)
            .ToList()
            .ForEach(b =>
            {
                try
                {
                    setValue(b);
                }
                catch { }
            });
            E.GetProperties().Where(b => b.GetObjectCustomAttribute <ConfigAttribute>() != null)
            .ToList()
            .ForEach(b =>
            {
                try
                {
                    setValue(b);
                }
                catch { }
            });



            LanguageManager.GetLang = () =>
            {
                var obj = getSession((string)LanguageManager.LanguageKey);
                if (obj == null)
                {
                    return(G.DefaultLanguage);
                }
                return(obj.MyTryConvert <int>());
            };
            LanguageManager.SetLang = (lang) =>
            {
                setSession((string)LanguageManager.LanguageKey, lang);
            };

            if (G.UseContentRouter)
            {
                RouteTable.Routes.MapRoute("content", $"{(String.IsNullOrEmpty(G.ContentPageUrl) ? "" : G.ContentPageUrl + "/")}{{*names}}",
                                           defaults: new { controller = "SDHCPage", action = "Index" });
            }
        }
예제 #21
0
 public static ApplicationUserManager UserManager()
 {
     return(OwinContextExtensions.Get <ApplicationUserManager>(GetContext()));
 }
예제 #22
0
 public static ApplicationSignInManager SignManager()
 {
     return(OwinContextExtensions.Get <ApplicationSignInManager>(GetContext()));
 }
예제 #23
0
        public static ApplicationUserManager Create(
            IdentityFactoryOptions <ApplicationUserManager> options,
            IOwinContext context)
        {
            ApplicationUserManager          applicationUserManager1 = new ApplicationUserManager((IUserStore <ApplicationUser>) new UserStore <ApplicationUser>((DbContext)OwinContextExtensions.Get <ApplicationDbContext>(context)));
            ApplicationUserManager          applicationUserManager2 = applicationUserManager1;
            UserValidator <ApplicationUser> userValidator1          = new UserValidator <ApplicationUser>((UserManager <ApplicationUser, string>)applicationUserManager1);

            ((UserValidator <ApplicationUser, string>)userValidator1).set_AllowOnlyAlphanumericUserNames(false);
            ((UserValidator <ApplicationUser, string>)userValidator1).set_RequireUniqueEmail(true);
            UserValidator <ApplicationUser> userValidator2 = userValidator1;

            ((UserManager <ApplicationUser, string>)applicationUserManager2).set_UserValidator((IIdentityValidator <ApplicationUser>)userValidator2);
            ApplicationUserManager applicationUserManager3 = applicationUserManager1;
            PasswordValidator      passwordValidator1      = new PasswordValidator();

            passwordValidator1.set_RequiredLength(6);
            passwordValidator1.set_RequireNonLetterOrDigit(true);
            passwordValidator1.set_RequireDigit(true);
            passwordValidator1.set_RequireLowercase(true);
            passwordValidator1.set_RequireUppercase(true);
            PasswordValidator passwordValidator2 = passwordValidator1;

            ((UserManager <ApplicationUser, string>)applicationUserManager3).set_PasswordValidator((IIdentityValidator <string>)passwordValidator2);
            ((UserManager <ApplicationUser, string>)applicationUserManager1).set_UserLockoutEnabledByDefault(true);
            ((UserManager <ApplicationUser, string>)applicationUserManager1).set_DefaultAccountLockoutTimeSpan(TimeSpan.FromMinutes(5.0));
            ((UserManager <ApplicationUser, string>)applicationUserManager1).set_MaxFailedAccessAttemptsBeforeLockout(5);
            ApplicationUserManager applicationUserManager4 = applicationUserManager1;
            PhoneNumberTokenProvider <ApplicationUser> numberTokenProvider1 = new PhoneNumberTokenProvider <ApplicationUser>();

            ((PhoneNumberTokenProvider <ApplicationUser, string>)numberTokenProvider1).set_MessageFormat("Your security code is {0}");
            PhoneNumberTokenProvider <ApplicationUser> numberTokenProvider2 = numberTokenProvider1;

            ((UserManager <ApplicationUser, string>)applicationUserManager4).RegisterTwoFactorProvider("Phone Code", (IUserTokenProvider <ApplicationUser, string>)numberTokenProvider2);
            ApplicationUserManager applicationUserManager5           = applicationUserManager1;
            EmailTokenProvider <ApplicationUser> emailTokenProvider1 = new EmailTokenProvider <ApplicationUser>();

            ((EmailTokenProvider <ApplicationUser, string>)emailTokenProvider1).set_Subject("Security Code");
            ((EmailTokenProvider <ApplicationUser, string>)emailTokenProvider1).set_BodyFormat("Your security code is {0}");
            EmailTokenProvider <ApplicationUser> emailTokenProvider2 = emailTokenProvider1;

            ((UserManager <ApplicationUser, string>)applicationUserManager5).RegisterTwoFactorProvider("Email Code", (IUserTokenProvider <ApplicationUser, string>)emailTokenProvider2);
            ((UserManager <ApplicationUser, string>)applicationUserManager1).set_EmailService((IIdentityMessageService) new EmailService());
            ((UserManager <ApplicationUser, string>)applicationUserManager1).set_SmsService((IIdentityMessageService) new SmsService());
            IDataProtectionProvider protectionProvider = options.get_DataProtectionProvider();

            if (protectionProvider != null)
            {
                ((UserManager <ApplicationUser, string>)applicationUserManager1).set_UserTokenProvider((IUserTokenProvider <ApplicationUser, string>) new DataProtectorTokenProvider <ApplicationUser>(protectionProvider.Create(new string[1]
                {
                    "ASP.NET Identity"
                })));
            }
            return(applicationUserManager1);
        }
예제 #24
0
 public static BankUserManager Create(IdentityFactoryOptions <BankUserManager> options, IOwinContext context)
 {
     return(new BankUserManager(new UserStore <BankAccount>(OwinContextExtensions.Get <BankDbContext>(context))));
 }
예제 #25
0
 public DbRepository()
 {
     context = OwinContextExtensions.Get <AppIdentityDbContext>(HttpContext.Current.GetOwinContext());
 }