Example #1
1
        public async Task SetupAsync()
        {
            _evnt = new EventViewModel
            {
                Title = "Title event",
                Description = "Test event",
                Start = "11:00",
                End = "14:27",
                Date = "2016-02-01"
            };

            var userViewModel = new LoginViewModel
            {
                Email = "[email protected]",
                Password = "useruser",
                RememberMe = false
            };
            var context = new DataContext();
            var manager = new UserManager(new UserStore(context));
            var user = await manager.FindAsync(userViewModel.Email, userViewModel.Password);
            if (user == null)
            {
                await manager.CreateAsync(new User { Email = userViewModel.Email, UserName = userViewModel.Email }, userViewModel.Password);
            }
            _calendarController = new CalendarController(context);

            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _calendarController.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _calendarController.AuthenticationManager = mockAuthenticationManager.Object;
        }
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            // password for jwmcpeak is [email protected]
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var user = await userManager.FindAsync(model.Username, model.Password);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "The user with the supplied credentials does not exist.");
                return View(model);
            }

            var authManager = HttpContext.GetOwinContext().Authentication;
            var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            authManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);

            return RedirectToAction("index", "home");
        }
 public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
 {
     context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"});
     try
     {
         using (var userManager = new UserManager<User>(new UserStore<User>(new ElearningDbContext())))
         {
             var user = await userManager.FindAsync(context.UserName, context.Password);
             if (user == null)
             {
                 context.SetError("invaild_grant", "The user name or password is incorrect");
                 return;
             }
         }
     }
     catch (Exception ex)
     {
         var a = ex;
         throw;
     }
     var identity = new ClaimsIdentity("JWT");
     identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
     identity.AddClaim(new Claim("sub", context.UserName));
     identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
     var properties = new AuthenticationProperties(new Dictionary<string, string>
     {
         {
             "audience", context.ClientId ?? string.Empty
         }
     });
     var ticket = new AuthenticationTicket(identity, properties);
     context.Validated(ticket);
 }
Example #4
0
 public async Task<string> GetAuthKey(string username, string password)
 {
     var store = new ApplicationDbContext();
     var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(store));
     var user =await UserManager.FindAsync(username, password);
     var key=Guid.NewGuid().ToString();
     user.Logins.Add(new IdentityUserLogin { LoginProvider="app",ProviderKey=key,UserId=user.Id});
     store.SaveChanges();
     return key;
 }
		/// <summary>
		/// Invoked after the LTI request has been authenticated so the application can sign in the application user.
		/// </summary>
		/// <param name="context">Contains information about the login session as well as the LTI request.</param>
		/// <param name="claims">Optional set of claims to add to the identity.</param>
		/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
		public static async Task OnAuthenticated(LtiAuthenticatedContext context, IEnumerable<Claim> claims = null)
		{
			// Find existing pairing between LTI user and application user
			var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new LtiDb()));
			var loginProvider = string.Join(":", new[] { context.Options.AuthenticationType, context.LtiRequest.ConsumerKey });
			var providerKey = context.LtiRequest.UserId;
			var login = new UserLoginInfo(loginProvider, providerKey);
			var user = await userManager.FindAsync(login);
			if (user == null)
			{
				var usernameContext = new LtiGenerateUserNameContext(context.OwinContext, context.LtiRequest);
				await context.Options.Provider.GenerateUserName(usernameContext);
				if (string.IsNullOrEmpty(usernameContext.UserName))
				{
					return;
				}
				user = await userManager.FindByNameAsync(usernameContext.UserName);
				if (user == null)
				{
					user = new ApplicationUser { UserName = usernameContext.UserName };
					var result = await userManager.CreateAsync(user);
					if (!result.Succeeded)
					{
						return;
					}
				}
				// Save the pairing between LTI user and application user
				await userManager.AddLoginAsync(user.Id, login);
			}

			// Create the application identity, add the LTI request as a claim, and sign in
			var identity = await userManager.CreateIdentityAsync(user, context.Options.SignInAsAuthenticationType);
			identity.AddClaim(new Claim(context.Options.ClaimType, JsonConvert.SerializeObject(context.LtiRequest, Formatting.None,
					new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }), ClaimValueTypes.String, context.Options.AuthenticationType));
			if (claims != null)
			{
				foreach (var claim in claims)
				{
					identity.AddClaim(claim);
				}
			}
			context.OwinContext.Authentication.SignIn(new AuthenticationProperties { IsPersistent = false }, identity);

			// Redirect to original URL so the new identity takes affect
			context.RedirectUrl = context.LtiRequest.Url.ToString();
		}
        // GET: ClaimsIdentityFactory
        public async Task<ActionResult> Index(LoginViewModel model, string returnUrl)
        {
            var context = new MyDbContext();
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            userManager.ClaimsIdentityFactory = new MyClaimsIdentityFactory<ApplicationUser>();

            // Create a User to SignIn
            var user = await userManager.FindAsync(model.UserName, model.Password);

            //SignIn the User by generating a ClaimsIdentity            
            var claimsIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            // This claimsIdentity should have a claim called LastLoginTime
            var authManager = HttpContext.GetOwinContext().Authentication;
            authManager.SignIn(claimsIdentity);
            
            return RedirectToLocal(returnUrl);
        }
Example #7
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var userStore = new UserStore<ApplicationUser>(new DataContext());
            var userManager = new UserManager<ApplicationUser>(userStore);
        var user = await  userManager.FindAsync(model.Email, model.Password);
            if (user != null)
            {
                ModelState.AddModelError(string.Empty, "Пользователь существует");
                return View(model);
            }

            user = new ApplicationUser { UserName = model.Email, Email = model.Email };
           await userManager.CreateAsync(user, model.Password);
            return RedirectToAction("Index", "Home");
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = new UserManager<User>(new UserStore<User>(new DatabaseContext()));

            var user = await userManager.FindAsync(context.UserName, context.Password);

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

            var oAuthIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);
            var cookiesIdentity = await userManager.CreateIdentityAsync(user, CookieAuthenticationDefaults.AuthenticationType);

            var properties = CreateProperties(user.UserName);
            var ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
Example #9
0
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var userStore = new UserStore<ApplicationUser>(new DataContext());
            var userManager = new UserManager<ApplicationUser>(userStore);
            var user = await userManager.FindAsync(model.Email, model.Password);
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Пользователь с такой комбинацией пароля и логина не существует");
                return View(model);
            }
            var authManager = HttpContext.GetOwinContext().Authentication;
            var userIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            authManager.SignIn(new Microsoft.Owin.Security.AuthenticationProperties { IsPersistent = model.RememberMe }, userIdentity);

            return RedirectToLocal(returnUrl);
        }
		public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) {

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

			AuthContext _ctx = new AuthContext();
			using (UserManager<IdentityUser> _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx))) {
				IdentityUser 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("sub", context.UserName));
			identity.AddClaim(new Claim("role", "user"));
			identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

			context.Validated(identity);

		}
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                // カスタマイズのポイント:
                //   UserManagerのインスタンス作成時、
                //     型引数:カスタマイズしたユーザー情報
                //     コンストラクタの引数:カスタマイズしたユーザストアのインスタンス
                //   をそれぞれ渡す
                var userManager = new UserManager<MyAppUser>(new MyAppUserStore());

                // カスタマイズのポイント:
                //   パスワードのハッシュ化アルゴリズムとして、IPasswordHasherを実装したカスタムクラスのインスタンスを設定
                userManager.PasswordHasher = new MyPasswordHasher();

                var user = await userManager.FindAsync(model.UserName, model.Password);
                if (user != null)
                {
                    var authentication = this.HttpContext.GetOwinContext().Authentication;
                    var identify = await userManager.CreateIdentityAsync(
                        user,
                        DefaultAuthenticationTypes.ApplicationCookie);
                    authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    authentication.SignIn(new AuthenticationProperties() { IsPersistent = false }, identify);

                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError("", "ログインIDまたはパスワードが無効です。");
                    
                }
            }

            // ここで問題が発生した場合はフォームを再表示します
            return View(model);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (var dbContext = new InstantDeliveryContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(dbContext));
                User user = await userManager.FindAsync(context.UserName, context.Password);

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

                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);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = await userManager.FindAsync(model.Username, model.Password);

            if (user != null)
            {
                ModelState.AddModelError(string.Empty, "The user already exists.");
                return View(model);
            }

            user = new IdentityUser { UserName = model.Username, Email = model.Email };

            await userManager.CreateAsync(user, model.Password);

            return RedirectToAction("index", "home");
        }
Example #14
0
		public static async void ConfigureUsers(IEnumerable<InMemoryUser> users, EntityFrameworkServiceOptions options, UserManager userManager) {
			using(var db = new Contexto(options.ConnectionString)) {
				
				if(!db.Users.Any()) {
					
					foreach(var u in users) {
						var entity = new Usuario { Email = u.Claims.First(x=>x.Type==Constants.ClaimTypes.Email).Value , UserName = u.Username };
						var response = await userManager.CreateAsync(entity, u.Password);
						
						if(!response.Succeeded) {
							throw new Exception("Não foi possível criar o usuario" + u.Username + response.Errors.ToString());
						}
						else {
							
							var user = await userManager.FindAsync(u.Username,u.Password);
							foreach(var c in u.Claims) {

								await userManager.AddClaimAsync(user.Id,c);
							}
														
							await userManager.UpdateAsync(user);
						}
					}
					db.SaveChanges();
				}
			}
		}
        public async Task<JsonData> Login(LoginModel model)
        {
            try
            {
                using (var db = new DataContext())
                {
                    var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));

                    //get the user by the email address
                    var us = new UserRepo().GetUserByName(model.UserName, db);
                    if (us == null) throw new Exception("Please check the login details");

                    var user = await userMan.FindAsync(us.UserName, model.Password);
                    if (user == null) throw new Exception("Please check the login details");

                    if (!user.IsActive) throw new Exception("You can not login because your user is not active");

                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
                    var identity = await userMan.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, identity);

                    var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
                    var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);

                    return DataHelpers.ReturnJsonData(user, true, token);
                }
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            //try { 
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

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

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

            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            if (!user.EmailConfirmed)
            {
                context.SetError("invalid_grant", "User did not confirm email.");
                return;
            }


            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            user.Roles.ToList().ForEach(r =>
            {
                var role = roleManager.FindById(r.RoleId);
                identity.AddClaim(new Claim(ClaimTypes.Role, role.Name)); 
            });
            
            identity.AddClaim(new Claim("sub", context.UserName));

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

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
            //}
            //catch (Exception ex)
            //{
            //    throw;
           // }
        }
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }


            List<Tenant> tenants = new List<Tenant>();
            tenants.Add(new Tenant() { Id = 1, Name = "K Force", DbContext = "KforceDB", Email = "[email protected]" });
            tenants.Add(new Tenant() { Id = 2, Name = "Sudeep Company", DbContext = "SudeepDB", Email = "[email protected]" });

            string dbContext = tenants.First(x => x.Id == model.TenantId).DbContext;

            ApplicationDbContext _db= new ApplicationDbContext(dbContext);
            UserManager<ApplicationUser> _myUserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_db));

            var user = await _myUserManager.FindAsync("tcadmin", model.Password);
            if (user != null)
            {
                var claim = await _myUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
                AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, claim);
                return RedirectToAction("Index", "Admin");
            }


            //_myUserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
            ViewData["Tenants"] = (from t in tenants
                                   select new SelectListItem()
                                   {
                                       Text = t.Name,
                                       Value = t.Id.ToString()
                                   }).ToList();
            return View(model);
        }
Example #18
-6
        public async Task SetupAsync()
        {
            _userViewModel = new LoginViewModel
            {
                Email = "[email protected]",
                Password = "useruser",
                RememberMe = false
            };
            var context = new DataContext();
            _manager = new UserManager(new UserStore(context));
            _controller = new AccountController(_manager);

            var user = await _manager.FindAsync(_userViewModel.Email, _userViewModel.Password);
            if (user == null)
            {
                await _manager.CreateAsync(new User { Email = _userViewModel.Email, UserName = _userViewModel.Email }, _userViewModel.Password);
            }
            var mockCp = new Mock<IClaimsPrincipal>();
            if (user != null) mockCp.SetupGet(cp => cp.UserId).Returns(user.Id);
            _controller.CurrentUser = mockCp.Object;

            var mockAuthenticationManager = new Mock<IAuthenticationManager>();
            mockAuthenticationManager.Setup(am => am.SignOut());
            mockAuthenticationManager.Setup(am => am.SignIn());
            _controller.AuthenticationManager = mockAuthenticationManager.Object;
        }