public async Task CheckLoginAsync() { string login = RandomDigits(20); string pswd = RandomDigits(20); string lastName = RandomDigits(20); string firstName = RandomDigits(20); string email = "*****@*****.**"; RegistrationUser regUser = new RegistrationUser() { Login = login, Password = pswd, LastName = lastName, FirstName = firstName, Email = email }; AuthenticationUser authUser = new AuthenticationUser() { Login = login, Password = pswd }; AuthenticationService _service = new AuthenticationService(); //try to login unregisted user _ = Assert.ThrowsAsync <Exception>(() => _service.AuthenticateAsync(authUser)); _ = await _service.RegisterUserAsync(regUser); var user = await _service.AuthenticateAsync(authUser); Assert.Equal(login, user.Login); }
#pragma warning disable 1998 public override async Task <CommandResult> ExecuteAsync(CancellationToken cancel) { string authUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl(); Console.WriteLine($"Go to following URL and authenticate: {authUrl}"); Console.WriteLine("Paste the returned URL and press ENTER: "); string redirectUrl = Console.ReadLine(); try { WindowsLiveResponse response = AuthenticationService .ParseWindowsLiveResponse(redirectUrl); AuthenticationService authService = new AuthenticationService(response); await authService.AuthenticateAsync(); await authService.DumpToJsonFileAsync(TokenFilePath); } catch (Exception e) { Console.WriteLine($"Authentication failed! {e.Message}"); return(CommandResult.RuntimeFailure); } Console.WriteLine($"Authentication succeeded, tokens saved to {TokenFilePath}"); return(CommandResult.Success); }
[InlineData(Email, "PASSWORD", false)] // Password casing public async Task Authenticate_GivenCredentials_VerifiesPasswordAndEmail(string email, string password, bool shouldWork) { GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output); // Arrange using (IDatabaseContext context = getContext()) { EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe()); userEntry.Entity.Email = Email; userEntry.Entity.PasswordHash = PasswordHash; await context.SaveChangesAsync(); } // Act var passwordServiceMock = new Mock <IPasswordService>(); passwordServiceMock.Setup(p => p.NeedsRehash(PasswordHash)).Returns(false); passwordServiceMock.Setup(p => p.VerifyPassword(Password, PasswordHash)).Returns(true); var authenticationService = new AuthenticationService(passwordServiceMock.Object, getContext, DummyLogger <AuthenticationService>()); (bool isAuthenticated, _) = await authenticationService.AuthenticateAsync(email, password); // Assert passwordServiceMock.Verify(p => p.VerifyPassword(password, PasswordHash), Times.AtMostOnce); if (shouldWork) { passwordServiceMock.Verify(p => p.NeedsRehash(PasswordHash), Times.Once); } Assert.Equal(shouldWork, isAuthenticated); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } var user = await _authenticationService.AuthenticateAsync(model.Username, model.Password); if (user != null) { // Ensure stages can be created await _stageClient.EnsureOwnerCreated(user.Username); // Login var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Username)); claims.Add(new Claim(ClaimTypes.Name, user.Username)); claims.Add(new Claim(ClaimTypes.Email, user.EmailAddress)); var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); var authenticationManager = Request.GetOwinContext().Authentication; authenticationManager.SignIn(identity); return(RedirectToLocal(returnUrl)); } SetUiMessage(UiMessageTypes.Error, "The username or password is invalid."); return(RedirectToAction("Login", new { returnUrl = returnUrl })); }
private async void SignIn() { if (String.IsNullOrWhiteSpace(Login) || String.IsNullOrWhiteSpace(Password)) { MessageBox.Show("Login or password is empty."); } else { var authService = new AuthenticationService(); User user = null; try { IsEnabled = false; user = await authService.AuthenticateAsync(_authUser); } catch (Exception ex) { MessageBox.Show($"Sign In failed: {ex.Message}"); return; } finally { IsEnabled = true; } MessageBox.Show($"Sign In was successful for user {user.FirstName} {user.LastName}"); _gotoWallets.Invoke(); } }
public async Task ShouldLoadExistingAccountIfCached() { const string keyInPemFormat = "--- not actually a pem ---"; var options = TestHelper.GetStagingOptions(); var accountFilename = $"{options.CertificateAuthorityUri.Host}--{options.Email}.pem"; // arrange // verify key is pulled from storage var storageMock = new Mock <IStorageProvider>(); storageMock.Setup(x => x.Escape(It.IsAny <string>())) .Returns(accountFilename); storageMock.Setup(x => x.ExistsAsync("account/" + accountFilename, It.IsAny <CancellationToken>())) .Returns(Task.FromResult(true)); storageMock.Setup(x => x.GetAsync("account/" + accountFilename, It.IsAny <CancellationToken>())) .Returns(Task.FromResult(keyInPemFormat)); var keyMock = new Mock <IKey>(); keyMock.Setup(x => x.ToPem()) .Returns(keyInPemFormat); var acmeContextMock = new Mock <IAcmeContext>(); acmeContextMock.SetupGet(x => x.AccountKey) .Returns(keyMock.Object); acmeContextMock.Setup(x => x.NewAccount(It.IsAny <IList <string> >(), true)) .Returns(Task.FromResult((IAccountContext)null)); var contextFactoryMock = acmeContextMock.Object.CreateFactoryMock(); var keyFactoryMock = new Mock <IAcmeKeyFactory>(); keyFactoryMock.Setup(x => x.FromPem(keyInPemFormat)) .Returns(keyMock.Object); var log = new Mock <ILogger <AuthenticationService> >(); IAuthenticationService authenticationService = new AuthenticationService(storageMock.Object, log.Object, contextFactoryMock.Object, keyFactoryMock.Object); // act var context = await authenticationService.AuthenticateAsync(options, CancellationToken.None); // assert context.Should().NotBeNull(); context.AcmeContext.Should().Be(acmeContextMock.Object); context.Options.Should().Be(options); // account was read from disk storageMock.Verify(x => x.GetAsync("account/" + accountFilename, It.IsAny <CancellationToken>())); // account was restored from key contextFactoryMock.Verify(x => x.GetContext(options.CertificateAuthorityUri, keyMock.Object)); // key was not written back to storage storageMock.Verify(x => x.SetAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Never); }
private async Task <bool> SignInWithPasswordAsync(string userName, string password) { var result = await AuthenticationService.AuthenticateAsync(userName, password); if (result.IsOk) { return(true); } await DialogBox.ShowAsync(result); return(false); }
public async Task <IActionResult> Login([FromBody] string password) { var foundPassword = await auth.AuthenticateAsync(password); if (foundPassword == null) { return(Unauthorized()); } string token = jwt.GenerateJSONWebToken(); return(Ok(new { token })); }
public async Task Authenticate_ReturnErrorResponse_ForWrongPassword() { // Arrange var mockUser = new User { UserName = "******" }; var mockUserDto = new UserDto { Username = "******" }; var mockLoginModel = new LoginModel { Username = "******", Password = "******" }; var mockJwtService = new Mock <IJwtService>(); mockJwtService.Setup(x => x.GenerateJwtToken(mockUser)).Returns(new JwtSecurityToken()); var mockMapper = new Mock <IMapper>(); mockMapper.Setup(x => x.Map <UserDto>(mockUser)).Returns(mockUserDto); var mockRoleStore = new Mock <IRoleStore <IdentityRole> >(); var mockRoleManager = new Mock <RoleManager <IdentityRole> >(mockRoleStore.Object, null, null, null, null); var mockUserStore = new Mock <IUserStore <User> >(); var mockUserManager = new Mock <UserManager <User> >(mockUserStore.Object, null, null, null, null, null, null, null, null); mockUserManager.Setup(x => x.FindByNameAsync(mockLoginModel.Username)).ReturnsAsync(mockUser); mockUserManager.Setup(x => x.CheckPasswordAsync(mockUser, mockLoginModel.Password)).ReturnsAsync(false); // Act var service = new AuthenticationService( mockRoleManager.Object, mockUserManager.Object, mockJwtService.Object, mockMapper.Object); var result = await service.AuthenticateAsync(mockLoginModel); // Assert result.Should().BeOfType <LoginResponse>(); result.Result.Should().BeFalse(); result.Status.Should().Be(ResponseStatus.Error); result.Item.Should().BeNull(); result.Token.Should().BeNull(); }
public void AuthenticateThrowsValidationException() { var singInManagerMock = new Mock <FakeSignInManager>(); var userManagerMock = new Mock <FakeUserManager>(); var jwtTokenFactoryMock = new Mock <IJwtTokenFactory>(); var unitOfWorkMock = new Mock <IUnitOfWork>(); singInManagerMock.Setup(x => x.PasswordSignInAsync(UserName, Password, false, false)).Returns(Task.FromResult(SignInResult.Failed)); userManagerMock.Setup(x => x.Users).Returns(Users.AsQueryable()); jwtTokenFactoryMock.Setup(x => x.GenerateJwt(UserName, User)).Returns(Token); var authenticationService = new AuthenticationService(singInManagerMock.Object, userManagerMock.Object, unitOfWorkMock.Object, jwtTokenFactoryMock.Object); Assert.ThrowsAsync <ValidationException>(async() => await authenticationService.AuthenticateAsync(UserName, Password)); }
static async Task <int> RunOAuth(OAuthOptions args) { Console.WriteLine(":: OAUTH ::"); if (String.IsNullOrEmpty(args.ResponseUrl)) { string requestUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl(); Console.WriteLine("1) Open following URL in your WebBrowser:\n\n{0}\n\n" + "2) Authenticate with your Microsoft Account\n" + "3) Execute application again with returned URL from addressbar as the argument\n", requestUrl); } else { try { WindowsLiveResponse response = AuthenticationService.ParseWindowsLiveResponse(args.ResponseUrl); AuthenticationService authenticator = new AuthenticationService(response); Console.WriteLine("Attempting authentication with Xbox Live..."); bool success = await authenticator.AuthenticateAsync(); if (!success) { throw new Exception("Authentication failed!"); } Console.WriteLine("Authentication succeeded"); if (!String.IsNullOrEmpty(args.TokenFilepath)) { success = await authenticator.DumpToJsonFileAsync(args.TokenFilepath); if (!success) { Console.WriteLine($"Failed to dump tokens to {args.TokenFilepath}"); return(2); } Console.WriteLine($"Tokens saved to {args.TokenFilepath}"); } } catch (Exception exc) { Console.WriteLine("Authentication failed! Error: " + exc.Message); return(1); } } return(0); }
public async Task AuthenticateReturnsToken() { var singInManagerMock = new Mock <FakeSignInManager>(); var userManagerMock = new Mock <FakeUserManager>(); var jwtTokenFactoryMock = new Mock <IJwtTokenFactory>(); var unitOfWorkMock = new Mock <IUnitOfWork>(); singInManagerMock.Setup(x => x.PasswordSignInAsync(UserName, Password, false, false)).Returns(Task.FromResult(SignInResult.Success)); userManagerMock.Setup(x => x.Users).Returns(Users.AsQueryable()); jwtTokenFactoryMock.Setup(x => x.GenerateJwt(UserName, User)).Returns(Token); var authenticationService = new AuthenticationService(singInManagerMock.Object, userManagerMock.Object, unitOfWorkMock.Object, jwtTokenFactoryMock.Object); var accessToken = await authenticationService.AuthenticateAsync(UserName, Password); Assert.Equal(accessToken.UserId, UserId); Assert.Equal(accessToken.UserName, UserName); Assert.Equal(accessToken.Token, Token); }
private async void btnLogIn_Click(object sender, EventArgs e) { try { lblError.Text = @"<b>Connecting to Server.</b><br/>Please Wait..."; OnConnectingProcess(true); var loginService = new AuthenticationService(Connection.CreateConnection().ConnectionString); var user = await loginService.AuthenticateAsync(txtUsername.Text, txtPassword.Text); if (user == null) { OnConnectingProcess(false); lblError.Text = @"<font color='Red'><b>Invalid Credential.</b><br/>Username or Password is Invalid</font>"; txtUsername.Focus(); txtUsername.SelectAll(); txtPassword.SelectAll(); return; } var token = loginService.GetCredentialToken(user.Username); App.CurrentUser.User = user; App.CurrentUser.Token = token; App.CurrentUser.User.RoleClass.RolePrivileges.LoadItemsFromDb(); App.LogAction("Account", "Logged In"); pbLogin.Visible = false; DialogResult = DialogResult.OK; } catch (Exception ex) { OnConnectingProcess(false); lblError.Text = $@"<font color='Red'>{ex.GetBaseException().Message}</font>"; // ex.GetBaseException().Message; txtUsername.Focus(); } }
public async Task ShouldAskForANewAccountIfNotCachedAndStoreAccountKey() { // arrange var storageMock = new Mock <IStorageProvider>(); storageMock.Setup(x => x.ExistsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult(false)); const string keyInPemFormat = "--- not actually a pem ---"; var keyMock = new Mock <IKey>(); keyMock.Setup(x => x.ToPem()) .Returns(keyInPemFormat); var acmeContextMock = new Mock <IAcmeContext>(); acmeContextMock.SetupGet(x => x.AccountKey) .Returns(keyMock.Object); acmeContextMock.Setup(x => x.NewAccount(It.IsAny <IList <string> >(), true)) .Returns(Task.FromResult((IAccountContext)null)); var factoryMock = acmeContextMock.Object.CreateFactoryMock(); var options = TestHelper.GetStagingOptions(); IAuthenticationService authenticationService = new AuthenticationService(storageMock.Object, factoryMock.Object); // act var context = await authenticationService.AuthenticateAsync(options, CancellationToken.None); // assert context.Should().NotBeNull(); context.AcmeContext.Should().Be(acmeContextMock.Object); context.Options.Should().Be(options); // ensure account wasn't read from disk storageMock.Verify(x => x.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.Never); factoryMock.Verify(x => x.GetContext(options.CertificateAuthorityUri, null)); // extension methods adds mailto to emailbefore calling the actual method acmeContextMock.Verify(x => x.NewAccount(It.Is <IList <string> >(list => list.Count == 1 && list[0] == $"mailto:{options.Email}"), true)); storageMock.Verify(x => x.SetAsync(It.IsAny <string>(), keyInPemFormat, It.IsAny <CancellationToken>())); }
public async Task <ActionResult <AuthenticationResponse> > Authenticate(AuthenticationRequest authenticationRequest) { try { var response = await _authenticationService.AuthenticateAsync(authenticationRequest, RepositoryManager.UserRepository); return(Ok(response)); } catch (AuthenticationException authException) { return(BadRequest(authException.ErrorMessage)); } catch (Exception err) { LogException(err); return(Problem()); } }
public async Task <ActionResult <AuthenticationResponse> > Token(AuthenticationRequest model) { try { return(Ok(await _authenticationService.AuthenticateAsync(model))); } catch (AuthenticationServiceForbiddenException) { return(Forbid()); } catch (AuthenticationServiceUnauthorizedException) { return(Unauthorized()); } catch (Exception ex) { return(StatusCode(500, $"Unexpected exception: {ex.Message}.")); } }
static async Task <int> RunHeadlessAuth(HeadlessOptions args) { Console.WriteLine(":: Headless ::"); var authUrl = AuthenticationService.GetWindowsLiveAuthenticationUrl(); try { var headlessAuthService = new HeadlessAuthenticationService(authUrl); headlessAuthService.ChooseAuthStrategyCallback = ChooseAuthStrategy; headlessAuthService.VerifyPosessionCallback = VerifyProof; headlessAuthService.EnterOneTimeCodeCallback = EnterOneTimeCode; var response = await headlessAuthService.AuthenticateAsync(args.Email, args.Password); var authenticator = new AuthenticationService(response); bool success = await authenticator.AuthenticateAsync(); Console.WriteLine("Authentication succeeded"); if (!String.IsNullOrEmpty(args.TokenFilepath)) { success = await authenticator.DumpToJsonFileAsync(args.TokenFilepath); if (!success) { Console.WriteLine($"Failed to dump tokens to {args.TokenFilepath}"); return(2); } Console.WriteLine($"Tokens saved to {args.TokenFilepath}"); } } catch (Exception exc) { Console.WriteLine("Headless authentication failed, error: " + exc.Message); return(1); } return(0); }
public async Task Authenticate_GivenPasswordWhichNeedsRehash_RehashesPassword() { GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output); const string NewPasswordHash = "NewPasswordHash"; // Arrange using (IDatabaseContext context = getContext()) { EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe()); userEntry.Entity.Email = Email; userEntry.Entity.PasswordHash = PasswordHash; await context.SaveChangesAsync(); } // Act var passwordServiceMock = new Mock <IPasswordService>(); passwordServiceMock.Setup(p => p.NeedsRehash(PasswordHash)).Returns(true); passwordServiceMock.Setup(p => p.VerifyPassword(Password, PasswordHash)).Returns(true); passwordServiceMock.Setup(p => p.HashPassword(Password)).Returns(NewPasswordHash); var authenticationService = new AuthenticationService(passwordServiceMock.Object, getContext, DummyLogger <AuthenticationService>()); (bool isAuthenticated, _) = await authenticationService.AuthenticateAsync(Email, Password); // Assert passwordServiceMock.Verify(p => p.NeedsRehash(PasswordHash), Times.Once); passwordServiceMock.Verify(p => p.HashPassword(Password), Times.Once); Assert.True(isAuthenticated); using (IDatabaseContext context = getContext()) { User user = context.Users.Single(); Assert.Equal(NewPasswordHash, user.PasswordHash); } }
// Need *async* here private async void button_Login_Click(object sender, EventArgs e) { var delayInMs = 5000; var authService = new AuthenticationService(); var authTask = authService.AuthenticateAsync(textBox_Username.Text, textBox_Password.Text, delayInMs); // We've already called the Authenticate method // You can do whatever here. We'll just log Log($"Authenticating. This takes {delayInMs / 1000} seconds..."); var authenticationResult = await authTask; if (authenticationResult) { MessageBox.Show(@"Login Success."); // Now, populate var pricesService = new PriceListSource(); var priceTask = pricesService.GetPricesAsync(); // Again, you can do whatever here. We'll just log. // In reality, you'd want to show a "Loading" gif, set your buttons to disabled and enable // them again when you're done. Log("Getting prices. This might take a while..."); var result = await priceTask; Log("After the await line, we're back in control!"); ShowPrices(result); Log("Done."); } else { MessageBox.Show(@"Access Denied."); // Do Nothing } }
public async Task <ActionResult <AuthenticationResponse> > Login(AuthenticationRequest request) { return(Ok(await AuthenticationService.AuthenticateAsync(request))); }
public async Task <IActionResult> Authenticate([FromBody] AuthenticationModel model) { var result = await _service.AuthenticateAsync(model); return(Ok(result)); }
public static async Task <UserAccount> AuthenticateAsync(string username, string password) { var service = new AuthenticationService(Connection.CreateConnection().ConnectionString); return(await service.AuthenticateAsync(username, password)); }