public Token Refresh(ServerDto serverDto, LoginDto loginDto, Token tokenToRefresh)
 {
     IAuthenticationService tokenService = null;
     if (serverDto.TokenType == TokenType.SAML)
         tokenService = new SamlTokenService(_webRequestManager);
     else
         tokenService = new JwtTokenService(_webRequestManager);
     return tokenService.Refresh(serverDto, loginDto, tokenToRefresh);
 }        
 public AuthTokenDto Login(ServerDto serverDto, LoginDto loginDto, string clientId)
 {
     IAuthenticationService tokenService = null;
     if(serverDto.TokenType == TokenType.SAML) 
         tokenService = new SamlTokenService(_webRequestManager);
     else 
         tokenService = new JwtTokenService(_webRequestManager);
     return tokenService.Authenticate(serverDto, loginDto, clientId);
 }
		public void OnClickLoginButton (object sender, EventArgs e)
		{
			if (string.IsNullOrEmpty (TxtUsername.StringValue)) {
				UIErrorHelper.ShowAlert ("Please enter valid username", "Alert");
			} else if (string.IsNullOrEmpty (TxtPassword.StringValue)) {
				UIErrorHelper.ShowAlert ("Please enter valid password", "Alert");
			} else {
				 LoginDto = new LoginDto () {
					User = TxtUsername.StringValue,
					Pass = TxtPassword.StringValue,
					TenantName = ServerDto.Tenant,
					DomainName = ServerDto.Tenant
				};
				this.Close ();
				NSApplication.SharedApplication.StopModalWithCode(1);
			}
		}
 public Token Refresh(ServerDto serverDto, LoginDto loginDto, Token tokenToRefresh)
 {
     var tenant = Uri.EscapeDataString(loginDto.TenantName);
     var url = string.Format(ServiceConfigManager.RefreshTokenEndPoint, serverDto.Protocol, serverDto.ServerName, serverDto.Port, tenant);
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
     var data = string.Format(ServiceConfigManager.RefreshTokenArguments, tokenToRefresh.RefreshToken, tokenToRefresh.ClientId);
     var requestConfig = new RequestSettings
     {
         Method = HttpMethod.Post,
     };
     var headers = ServiceHelper.AddHeaders();
     var result = _webRequestManager.GetResponse(url, requestConfig, headers, null, data);
     var token = JsonConvert.Deserialize<Token>(result);
     token.RefreshToken = tokenToRefresh.RefreshToken;
     token.ClientId = tokenToRefresh.ClientId;
     return token;
 }
        public AuthTokenDto Authenticate(ServerDto serverDto, LoginDto loginDto, string clientId)
        {
			var url = string.Format(ServiceConfigManager.SamlLegacyEndPoint, serverDto.Protocol, serverDto.ServerName, serverDto.Port, serverDto.StsUrl + "/" + loginDto.TenantName);
            string soapString = XmlResourceHelper.GetResourceXml("Vmware.Tools.RestSsoAdminSnapIn.Service.xml.SAMLRequest.xml");

            int lifeInSeconds = 300;
            var dt = DateTime.Now;
            dt = TimeZoneInfo.ConvertTimeToUtc(dt);
            var dtEnd = dt.AddSeconds(lifeInSeconds);
            string format = "yyyy-MM-ddTHH:mm:ss.fffZ";
            var pass = WrapInCDATA(loginDto.Pass);
            var principalName = loginDto.User + "@" + loginDto.DomainName;
            soapString = string.Format(soapString, dt.ToString(format), dtEnd.ToString(format), principalName, pass, dt.ToString(format), dtEnd.ToString(format));

            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            //var data = string.Format(ServiceConfigManager.LoginArguments, loginDto.User, loginDto.Pass, loginDto.DomainName, clientId);
            var requestConfig = new RequestSettings
            {
                Method = HttpMethod.Post,
            };
            var headers = ServiceHelper.AddHeaders("text/xml");
            var customHeaders = new Dictionary<string,string>();
            customHeaders.Add("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue");
            var responseFromServer = _webRequestManager.GetResponse(url, requestConfig, headers, customHeaders, soapString);

            XmlDocument doc = new XmlDocument();
            doc.PreserveWhitespace = false;
            using (var reader = new StringReader(responseFromServer))
                doc.Load(reader);
            var node = doc.GetElementsByTagName("saml2:Assertion")[0];
            var signature = doc.GetElementsByTagName("ds:SignatureValue")[0];
            var rawToken = string.Empty;
            if (node != null)
            {
                rawToken = node.OuterXml;
            }
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(rawToken);
            rawToken = Convert.ToBase64String(bytes);
            var token = new Token(rawToken, serverDto.TokenType) { Raw = rawToken, ClientId = clientId, Signature = signature.InnerXml,TokenType = TokenType.SAML.ToString()};
            return new AuthTokenDto(Refresh) { Token = token, ClaimsPrincipal = null, Login = loginDto, ServerDto = serverDto };
            throw new Exception(responseFromServer);
        }
 public AuthTokenDto Authenticate(ServerDto serverDto, LoginDto loginDto, string clientId)
 {
     var tenant = Uri.EscapeDataString(loginDto.TenantName);
     var url = string.Format(ServiceConfigManager.LoginEndPoint, serverDto.Protocol, serverDto.ServerName, serverDto.Port, tenant);
     ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
     var data = string.Format(ServiceConfigManager.LoginArguments, loginDto.User, loginDto.Pass, loginDto.DomainName, clientId);
     var requestConfig = new RequestSettings
     {
         Method = HttpMethod.Post,
     };
     var headers = ServiceHelper.AddHeaders();
     var result = _webRequestManager.GetResponse(url, requestConfig, headers, null, data);
     var token = JsonConvert.Deserialize<Token>(result);
     token.Raw = result;
     token.ClientId = clientId;
     token.TokenType = TokenType.Bearer.ToString();
     var certificates = GetCertificates(serverDto, loginDto.TenantName, CertificateScope.TENANT, token);
     var claimsPrincipal = Validate(serverDto, loginDto.User + "@" + loginDto.DomainName, certificates[certificates.Count - 1], loginDto.TenantName, token.IdToken);
     if (claimsPrincipal != null)
         return new AuthTokenDto(Refresh) { Token = token, ClaimsPrincipal = claimsPrincipal, Login = loginDto, ServerDto = serverDto };
     return new AuthTokenDto(Refresh) { Token = token, ClaimsPrincipal = claimsPrincipal, Login = loginDto, ServerDto = serverDto };
     //throw new AuthenticationException(@"Login Failure: Invalid username or password");
 }
		public void OnClickAddButton (object sender, EventArgs e)
		{
			ActionHelper.Execute (delegate() {
				if (string.IsNullOrEmpty (TxtServer.StringValue)) {
					UIErrorHelper.ShowAlert ("Server name cannot be empty", "Alert");
				} else if (!WebUtil.PingHost (TxtServer.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid server name or ip address", "Alert");
				} else if (string.IsNullOrEmpty (TxtPort.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid server STS port", "Alert");
				} else if (string.IsNullOrEmpty (TxtTenant.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid tenant name", "Alert");
				} else if (this.CbSaml.StringValue == "1" && string.IsNullOrEmpty (TxtStsEndpoint.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid STS endpoint", "Alert");
				} else if (string.IsNullOrEmpty (TxtUsername.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid username", "Alert");
				} else if (string.IsNullOrEmpty (TxtPassword.StringValue)) {
					UIErrorHelper.ShowAlert ("Please enter valid password", "Alert");
				} else {
					var legacy = this.CbSaml.StringValue == "1";
					ServerDto = new ServerDto () {
						ServerName = TxtServer.StringValue,
						Port = TxtPort.StringValue,
						Tenant = TxtTenant.StringValue,
						Protocol = CbSsl.StringValue == "1" ? "https" : "http",
						TokenType = legacy ? TokenType.SAML : TokenType.Bearer,
						Url = LblUrl.StringValue,
						StsUrl = string.IsNullOrEmpty(TxtStsEndpoint.StringValue) ? string.Empty : TxtStsEndpoint.StringValue
					};

					LoginDto = new LoginDto {
						User = TxtUsername.StringValue,
						Pass = TxtPassword.StringValue,
						DomainName = TxtTenant.StringValue,
						TenantName = TxtTenant.StringValue
					};
					NSApplication.SharedApplication.StopModalWithCode (1);

//					if(!_changeServer)
//					{
//						var mainWindowController = new MainWindowController (ServerDto);
//						mainWindowController.Window.MakeKeyAndOrderFront (this);
//					}
				}
			});
		}
        public Token Refresh(ServerDto serverDto, LoginDto loginDto, Token tokenToRefresh)
        {
			var auth = Authenticate (serverDto, loginDto, string.Empty);
			return auth.Token;
        }
		public void OnClickAddButton (object sender, EventArgs e)
		{
			if(IsValid())
			{
				var serverDto = new ServerDto {
					ServerName = TxtServer.StringValue,
					Tenant = TxtTenant.StringValue,
					Port = TxtPort.StringValue,
					Protocol = CbSsl.StringValue == "1" ? "https" : "http",
					TokenType = CbSaml.StringValue == "1" ? TokenType.SAML : TokenType.Bearer,
					Url = LblServerUrl.StringValue,
					StsUrl = string.IsNullOrEmpty(TxtStsUrl.StringValue) ? string.Empty : TxtStsUrl.StringValue
				};
				var login = new LoginDto {
					User = TxtUsername.StringValue,
					Pass = TxtPassword.StringValue,
					DomainName = TxtDomain.StringValue,
					TenantName = TxtTenant.StringValue
				};
				try {
					TxtIDTokenString.StringValue = string.Empty;
					TxtAccessTokenString.StringValue = string.Empty;
					TxtRefreshTokenString.StringValue = string.Empty;
					TxtSamlToken.StringValue = string.Empty;

					if (CbSaml.StringValue == "0") {
						if (RdoTypeGroup.SelectedTag == 1) {
							var auth = SnapInContext.Instance.ServiceGateway.Authentication.Login (serverDto, login, Constants.ClientId);
							PopulateToken (auth);
						}
					} else {
						if (RdoTypeGroup.SelectedTag == 1) {
							var auth = SnapInContext.Instance.ServiceGateway.SamlTokenService.Authenticate (serverDto, login, Constants.ClientId);
							var bytes = Convert.FromBase64String (auth.Token.AccessToken);
							var token = System.Text.Encoding.Default.GetString (bytes);
							TxtSamlToken.StringValue = token;
						}
					}
				}

				catch (WebException exp)
				{
					if (CbSaml.StringValue == "1") {
						if (exp != null && exp.Response != null) {
							var resp = new StreamReader (exp.Response.GetResponseStream ()).ReadToEnd ();
							UIErrorHelper.ShowAlert (resp, "Error");
							return;
						} else {
							UIErrorHelper.ShowAlert (exp.Message, "Error");
							return;
						}
					} else {
						
						if (exp.Response is HttpWebResponse) {
							var response = exp.Response as HttpWebResponse;
							if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) {
								var resp = new StreamReader (exp.Response.GetResponseStream ()).ReadToEnd ();
								var error = JsonConvert.Deserialize<AuthErrorDto> (resp);
								if (error != null) {
									if (error.Error == AuthError.InvalidToken) {
										UIErrorHelper.ShowAlert ("Token Expired", "Error");
									} else {
										UIErrorHelper.ShowAlert (error.Details, "Error");
									}
								}
							} else {
								if (response != null && response.StatusCode == HttpStatusCode.BadRequest && response.ContentType == "application/json;charset=UTF-8") {
									var resp = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
									var error = JsonConvert.Deserialize<AuthErrorDto> (resp);
									if (resp.Contains (AuthError.InvalidGrant)) {                               
										if (error != null) {                                  
											UIErrorHelper.ShowAlert ("Invalid username or password", "Error");
										} else {
											UIErrorHelper.ShowAlert (exp.Message + " Details: " + resp, "Error");
										}
									} else {
										UIErrorHelper.ShowAlert (exp.Message + " Details: " + resp, "Error");
									}
								} else if (response != null && response.ContentType == "application/json") {
									var resp = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
									UIErrorHelper.ShowAlert (exp.Message + " Details: " + resp, "Error");
								} else {
									UIErrorHelper.ShowAlert (exp.Message, "Error");
								}
							}
						} else {
							UIErrorHelper.ShowAlert (exp.Message, "Error");
						}
					}
				}
				catch (Exception exp)
				{
					UIErrorHelper.ShowAlert(exp.Message, "Error");
				}
			}
		}