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 void Configuration(IAppBuilder app) { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); MappingConfig.RegisterMapping(); ConfigureOAuth(app); app.UseCors(CorsOptions.AllowAll); UserManagerFactory = () => { var usermanager = new UserManager<IdentityEmployee>(new UserStore<IdentityEmployee>(new IdentityContext())); usermanager.UserValidator = new UserValidator<IdentityEmployee>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; RoleManagerFactory = () => { var rolemanager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new IdentityContext())); return rolemanager; }; }
public void ConfigureAuth(IAppBuilder app, HttpConfiguration config) { var userStore = config.DependencyResolver.GetService(typeof(IUserStore<ApplicationUser, Guid>)) as IUserStore<ApplicationUser, Guid>; var roleStore = config.DependencyResolver.GetService(typeof(IRoleStore<ApplicationRole, Guid>)) as IRoleStore<ApplicationRole, Guid>; UserManager = new UserManager<ApplicationUser, Guid>(userStore); RoleManager = new RoleManager<ApplicationRole, Guid>(roleStore); CompanyRepository = config.DependencyResolver.GetService(typeof(ICompanyRepository)) as ICompanyRepository; WidgetDefinitionRepository = config.DependencyResolver.GetService(typeof(IWidgetDefinitionRepository)) as IWidgetDefinitionRepository; var oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/api/v1/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider(UserManager) }; // Adds OAuth server (token generation) app.UseOAuthAuthorizationServer(oAuthServerOptions); // Adds bearer token processing to pipeline (token consumption) app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); Seed(); }
public void Configuration(IAppBuilder app) { var db = new ApplicationDbContext(); var userManager = new UserManager<User, int>(new UserStore(db)); var roleManager = new RoleManager<UserRole, int>(new RoleStore(db)); var sb = new StringBuilder(); var format = "{0, -3} | {1, -15} | {2, -30} | {3, -20}"; sb.AppendLine("ASP.NET Identity Users:\n"); sb.AppendLine(string.Format(format, "ID", "Username", "Email", "Role(s)")); sb.AppendLine("-----------------------------------------------------------------------------"); foreach (var user in userManager.Users.Include(u => u.Roles)) { sb.AppendLine(string.Format(format, user.Id, user.UserName, user.Email, string.Join(", ", user.Roles.Select(r => r.Name).ToArray()))); } sb.AppendLine("\n\nASP.NET Identity Roles:\n"); format = "{0, -3} | {1, -20}"; sb.AppendLine(string.Format(format, "ID", "Role")); sb.AppendLine("--------------------------"); foreach (var role in roleManager.Roles) { sb.AppendLine(string.Format(format, role.Id, role.Name)); } app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync(sb.ToString()); }); }
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var user = await UserManager.FindAsync(model.Email, model.Password); if (user != null) { await SignInAsync(user, model.RememberMe); ApplicationDbContext context = new ApplicationDbContext(); var UserManager1 = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var UserID = UserManager.FindByEmail(model.Email).Id; if (UserManager1.IsInRole(UserID, "Admin")) { return RedirectToAction("Index", "Home"); } return RedirectToLocal(returnUrl); } else { ModelState.AddModelError("", "Invalid username or password."); } } // If we got this far, something failed, redisplay form return View(model); }
// In this method we will create default User roles and Admin user for login private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new ApplicationUser(); user.Email = "Gaving30gmail.com"; string userPWD = "testPassword1."; var chkUser = UserManager.Create(user, userPWD); //Add default User to Role Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<IdentityUser> manager, IdentityUser user) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/auth/login"), ExpireTimeSpan = System.TimeSpan.FromMinutes(1), SlidingExpiration = true }); UserManagerFactory = () => { var usermanager = new UserManager<AppUser>( new UserStore<AppUser>(new AppDbContext())); // allow alphanumeric characters in username usermanager.UserValidator = new UserValidator<AppUser>(usermanager) { AllowOnlyAlphanumericUserNames = false }; // use out custom claims provider usermanager.ClaimsIdentityFactory = new AppUserClaimsIdentityFactory(); return usermanager; }; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager, ApplicationUser user) { var userIdentity = await manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; }
private async Task CreateAdminUser() { var username = "******";//ConfigurationManager.AppSettings["DefaultAdminUsername"]; var password = "******";//ConfigurationManager.AppSettings["DefaultAdminPassword"]; using (var context = new ApplicationDbContext()) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var role = new IdentityRole(RoleName); var result = await roleManager.RoleExistsAsync(RoleName); if (!result) { await roleManager.CreateAsync(role); } var user = await userManager.FindByNameAsync(username); if (user == null) { user = new ApplicationUser { UserName = username, Email = "*****@*****.**", First = "Big", Last="Admin Person" }; await userManager.CreateAsync(user, password); await userManager.AddToRoleAsync(user.Id, RoleName); } } }
public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(() => { var roleManager = new RoleManager<WebRole, Guid>(CsoContext.Db.WebRoles); return roleManager; }); app.CreatePerOwinContext(() => { var userManager = new UserManager<WebUser, Guid>(CsoContext.Db.WebUsers) { PasswordHasher = CsoContext.Db.WebUsers.PasswordHasher, }; return userManager; }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Login"), Provider = new CookieAuthenticationProvider(), CookieName = "auth", #if DEBUG ExpireTimeSpan = TimeSpan.FromMinutes(500), #else ExpireTimeSpan = TimeSpan.FromMinutes(10), #endif SlidingExpiration = true, }); }
/// <summary> /// Initializes a new instance of the <see cref="AccountController"/> class. /// </summary> /// <param name="personManager"> /// The person manager <see cref="UserManager{Person}"/> /// </param> /// <param name="emailManager"> /// The email Manager. /// </param> public AccountController( UserManager<Person> personManager, IEmailManager emailManager) { this.signInManager = new SignInManager<Person, string>(personManager, System.Web.HttpContext.Current.GetOwinContext().Authentication); this.personManager = personManager; this.emailManager = emailManager; }
internal void CreateUserAndRole() { using (var context = new WebDeveloperDbContext()) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var userManager = new UserManager<WebDeveloperUser>(new UserStore<WebDeveloperUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Here we create a Admin super user who will maintain the website var user = new WebDeveloperUser { UserName = "******", Email = "*****@*****.**" }; string userPassword = "******"; var userCreation = userManager.Create(user, userPassword); //Add default User to Role Admin if (userCreation.Succeeded) userManager.AddToRole(user.Id, "Admin"); } // creating Creating Manager role if (!roleManager.RoleExists("Manager")) { var role = new IdentityRole { Name = "Manager" }; roleManager.Create(role); } // creating Creating Employee role if (!roleManager.RoleExists("Employee")) { var role = new IdentityRole { Name = "Employee" }; roleManager.Create(role); } } }
public static UserManager<User> Create(IdentityFactoryOptions<UserManager<User>> options, IOwinContext context) { var userManager = new UserManager<User>(new UserStore()); userManager.UserLockoutEnabledByDefault = true; userManager.MaxFailedAccessAttemptsBeforeLockout = 5; userManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); return userManager; }
/// <summary> /// The configure user manager. /// </summary> /// <param name="userStore"> /// The user store. /// </param> /// <param name="app"> /// The app. /// </param> /// <returns> /// The <see cref="UserManager{Person}"/>. /// </returns> public static UserManager<Person> ConfigureUserManager(UserStore<Person> userStore, IAppBuilder app) { var userManager = new UserManager<Person>(userStore); userManager.UserValidator = new UserValidator<Person>(userManager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords userManager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults userManager.UserLockoutEnabledByDefault = true; userManager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); userManager.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. userManager.RegisterTwoFactorProvider( "Phone Code", new PhoneNumberTokenProvider<Person> { MessageFormat = "Your security code is {0}" }); userManager.RegisterTwoFactorProvider( "Email Code", new EmailTokenProvider<Person> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); ////this.EmailService = new EmailService(); ////this.SmsService = new SmsService(); if (app != null) { var dataProtectionProvider = app.GetDataProtectionProvider(); if (dataProtectionProvider != null) { userManager.UserTokenProvider = new DataProtectorTokenProvider<Person>(dataProtectionProvider.Create("ASP.NET Identity")); } } return userManager; }
public AccountController(UserManager<User> userManager) { UserManager = userManager; var userValidator = userManager.UserValidator as UserValidator<User, string>; // user email as user's name userValidator.AllowOnlyAlphanumericUserNames = false; if (Startup.DataProtectionProvider != null) { this.UserManager.UserTokenProvider = new DataProtectorTokenProvider<User>(Startup.DataProtectionProvider.Create("PasswordReset")); } }
public static bool IsInRole(string user, string role) { using (TasklyDbContext db = new TasklyDbContext()) { using (var store = new UserStore<TasklyUser>(db)) { using (var manager = new UserManager<TasklyUser>(store)) { return manager.IsInRole(user, role); } } } }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/auth/login") }); UserManagerFactory = () => { var userManager = new UserManager<AuthenticatedUser>(new UserStore<AuthenticatedUser>(_identities)); return userManager; }; }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); UserManagerFactory = () => { var usermanager = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(new MessageBoardContext())); // allow alphanumeric characters in username usermanager.UserValidator = new UserValidator<ApplicationUser>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; }
public void Configuration(IAppBuilder builder) { var userManager = new UserManager(); var cryptographyConfiguration = new CryptographyConfiguration( new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000)), new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000))); var formsAuthenticationConfiguration = new FormsAuthenticationConfiguration { RedirectUrl = "~/login", DisableRedirect = true, UserMapper = userManager, CryptographyConfiguration = cryptographyConfiguration }; builder .UseNancyAuth(formsAuthenticationConfiguration, userManager) .UseNancy(new AppBootstrapper(formsAuthenticationConfiguration, userManager)); }
// In this method we will create default User roles and Admin user for login private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // In Startup iam creating first Admin Role and creating a default Admin User if (!roleManager.RoleExists("Admin")) { // first we create Admin rool var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Admin"; roleManager.Create(role); //Creacion del superadmin var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPWD = "123456"; var chkUser = UserManager.Create(user, userPWD); //Rol por defecto que es Admin if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } // Creacion de nuevos roles if (!roleManager.RoleExists("Cliente")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "Cliente"; roleManager.Create(role); } }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { IdentityHelper.SignIn(manager, user, isPersistent: false); using (Logic.ShoppingCartActions usersShoppingCart = new Logic.ShoppingCartActions()) { String cartId = usersShoppingCart.GetCartId(); usersShoppingCart.MigrateCart(cartId, user.Id); } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
protected void SignIn(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(EmailAddress.Text, Password.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("~/Tracker.aspx"); } else { StatusText.Text = "Invalid username or password."; LoginStatus.Visible = true; } }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Auth/Login") }); UserManagerFactory = () => { var userManager = new UserManager<AppUser>( new UserStore<AppUser>(new QANotesContext())); // allow alphanumeric characters in username userManager.UserValidator = new UserValidator<AppUser>(userManager) { AllowOnlyAlphanumericUserNames = false }; return userManager; }; }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/auth/login") }); UserManagerFactory = () => { var usermanager = new UserManager<Member>( new UserStore<Member>(new CommunitySiteContext())); // allow alphanumeric characters in username usermanager.UserValidator = new UserValidator<Member>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); if (!roleManager.RoleExists("manager")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "manager"; roleManager.Create(role); } if (!roleManager.RoleExists("agent")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "agent"; roleManager.Create(role); } if (!roleManager.RoleExists("doctor")) { var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(); role.Name = "doctor"; roleManager.Create(role); } using (var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()))) using (var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))) { var user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "agent"); user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "manager"); user = um.FindByEmail("*****@*****.**"); um.AddToRole(user.Id, "doctor"); } }
public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions { AuthenticationType = "ApplicationCookie", LoginPath = new PathString("/Account/Login"), LogoutPath = new PathString("/Home/Index") }); UserManagerFactory = () => { var userManager = new UserManager<User>( new UserStore<User>(new ApplicationDbContext())); userManager.UserValidator = new UserValidator<User>(userManager) { AllowOnlyAlphanumericUserNames = false }; return userManager; }; }
private void createRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); var user = new ApplicationUser(); user.UserName = "******"; user.Email = "*****@*****.**"; string userPWD = "Test#1"; var chkUser = UserManager.Create(user, userPWD); if (chkUser.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); } } if (!roleManager.RoleExists("Educator")) { var role = new IdentityRole(); role.Name = "Educator"; roleManager.Create(role); } if (!roleManager.RoleExists("Student")) { var role = new IdentityRole(); role.Name = "Student"; roleManager.Create(role); } }
public void Configuration(IAppBuilder app) { // this is the same as before app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/auth/login") }); // configure the user manager UserManagerFactory = () => { var usermanager = new UserManager<IdentityUser>( new UserStore<IdentityUser>(new CLabanowskiContext())); // allow alphanumeric characters in username usermanager.UserValidator = new UserValidator<IdentityUser>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; }
public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/ui/auth/login") }); // configure the user manager UserManagerFactory = (session) => { var usermanager = new UserManager<ApplicationUser>( new UserStore<ApplicationUser>(session)); // allow alphanumeric characters in username usermanager.UserValidator = new UserValidator<ApplicationUser>(usermanager) { AllowOnlyAlphanumericUserNames = false }; return usermanager; }; }