Example #1
0
 public async Task AddDuplicateLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("dupeLogintest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     UnitTestHelper.IsFailure(await mgr.AddLoginAsync(user.Id, userLogin1));
 }
        public async Task Add_Should_Add_New_Login_Just_After_UserManager_CreateAsync_Get_Called()
        {
            const string userName = "Tugberk";
            const string loginProvider = "Twitter";
            const string providerKey = "12345678";

            using (IDocumentStore store = CreateEmbeddableStore())
            {
                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    RavenUserStore<RavenUser> userStore = new RavenUserStore<RavenUser>(ses);
                    UserManager<RavenUser> userManager = new UserManager<RavenUser>(userStore);

                    RavenUser user = new RavenUser(userName);
                    UserLoginInfo loginToAdd = new UserLoginInfo(loginProvider, providerKey);
                    await userManager.CreateAsync(user);
                    await userManager.AddLoginAsync(user.Id, loginToAdd);
                    await ses.SaveChangesAsync();
                }

                using (IAsyncDocumentSession ses = store.OpenAsyncSession())
                {
                    ses.Advanced.UseOptimisticConcurrency = true;
                    IUserLoginStore<RavenUser, string> userLoginStore = new RavenUserStore<RavenUser>(ses);
                    RavenUser user = await ses.LoadAsync<RavenUser>(RavenUser.GenerateKey(userName));
                    RavenUserLogin foundLogin = await ses.LoadAsync<RavenUserLogin>(RavenUserLogin.GenerateKey(loginProvider, providerKey));

                    // Assert
                    Assert.Equal(1, user.Logins.Count());
                    Assert.NotNull(foundLogin);
                }
            }
        }
Example #3
0
 public async Task AddLoginNullLoginFailsTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("Hao");
     UnitTestHelper.IsSuccess(await manager.CreateAsync(user));
     ExceptionHelper.ThrowsArgumentNull(() => AsyncHelper.RunSync(() => manager.AddLoginAsync(user.Id, null)),
         "login");
 }
Example #4
0
 public async Task LinkUnlinkDeletesTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var mgr = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
     var user = new IdentityUser("linkunlinktest");
     UnitTestHelper.IsSuccess(await mgr.CreateAsync(user));
     var userLogin1 = new UserLoginInfo("provider1", "p1-1");
     var userLogin2 = new UserLoginInfo("provider2", "p2-1");
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin1));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.AddLoginAsync(user.Id, userLogin2));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(2, (await mgr.GetLoginsAsync(user.Id)).Count);
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin1));
     Assert.Equal(0, user.Logins.Count(l => l.ProviderKey == "p1-1"));
     Assert.Equal(1, user.Logins.Count(l => l.ProviderKey == "p2-1"));
     Assert.Equal(1, (await mgr.GetLoginsAsync(user.Id)).Count());
     UnitTestHelper.IsSuccess(await mgr.RemoveLoginAsync(user.Id, userLogin2));
     Assert.Equal(0, (await mgr.GetLoginsAsync(user.Id)).Count);
     Assert.Equal(0, db.Set<IdentityUserLogin>().Count());
 }
		/// <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();
		}
 private static async System.Threading.Tasks.Task CreateUserIfNotExist(UserManager<ApplicationUser> userManager, string email, string password, string role, string loginProvider = null, string providerKey = null)
 {
     var user = await userManager.FindByEmailAsync(email);
     if (user == null)
     {
         user = new ApplicationUser { UserName = email, Email = email };
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
 }
Example #7
0
 private static async Task<ApplicationUser> CreateUserIfNotExist(UserManager<ApplicationUser> userManager, ApplicationUser user, string password, string role, string loginProvider = null, string providerKey = null)
 {
     //Debugger.Launch();
     user.EmailConfirmed = true;
     user.Email = user.Email ?? user.UserName;
     if (await userManager.FindByEmailAsync(user.Email) == null)
     {
         var result = await userManager.CreateAsync(user, password);
         if (!result.Succeeded)
         {
             throw new ApplicationException(string.Join("\n", result.Errors.Select(a => a.Description).ToArray()));
         }
         await userManager.AddToRoleAsync(user, role);
         if (loginProvider != null && providerKey != null)
         {
             await userManager.AddLoginAsync(user, new UserLoginInfo(loginProvider, providerKey, ""));
         }
     }
     return user;
 }