Selenium how to work with safari Cookies - selenium

I try to work with Selenium and have problem with cookies it return cookie equals null in method FindCookie, with Google Chrome and FireFox all works good
public void SetCookie(string cookieName, string cookieValue)
{
var cookie = new Cookie(cookieName, cookieValue);
driver.Manage().Cookies.AddCookie(cookie);
// driver.Manage().Cookies.AddCookie(new Cookie(cookieName, cookieValue, "/"));
}
public string FindCookie(string cookieName)
{
var cookieNamed = driver.Manage().Cookies.GetCookieNamed(cookieName);
if (cookieNamed == null)
return null;
return cookieNamed.Value;
}
How I can do works cookie for Safari?

Related

Proxy with CefSharp

how can I set up a proxy that has username and password in CefSharp browser in visual basic?
I tried with this code but doesn't work:
Dim proxy = "IP:PORT#USERNAME:PASSWORD"
Dim settings As New CefSettings()
settings.CefCommandLineArgs.Add("proxy-server", proxy)
Thanks
Your browser implement a IBrowser interface with GetHost method that allow you get RequestContext. You can set the proxy:
var requestContext = browser.GetHost().RequestContext;
var values = new Dictionary<string, object>
{
["mode"] = "fixed_servers",
["server"] = $"{proxyScheme}://{proxyHost}:{proxyPort}"
};
string error;
bool success = requestContext.SetPreference("proxy", values, out error);
To set user/password, you need to implement an IRequestHandler interface and implement this method:
public bool GetAuthCredentials(
IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
{
if (isProxy)
{
var browser2 = browserControl as IChromeRequestHandler;
var proxyOptions = browser2?.ProxySettings;
if (proxyOptions != null)
{
callback.Continue(proxyOptions.UserName, proxyOptions.Password);
return true;
}
}
callback.Dispose();
return false;
}
Then, you must set the RequestHandler property of your browser:
browser.RequestHandler = new YourIRequestHandlerImplementation();
Sorry for the C# implementation, but I think may be useful to you.

Securing swagger ui in asp.net core

First of all I should say that, I'm not native in English that may cause to misunderstanding on explanation.
This issue is about Securing swagger ui in ASP.Net Core as describe in this link I have done it and it works well in Mozilla Firefox, Microsoft edge and Opera explorer but it does not work in Google chrome.
Chrome opens the swagger api page with out any alert or login information.
Does anyone have a suggestion for configuration in startup.cs or any help on the subject?
Here I paste some codes that did to solve it but it does not work on Chrome.
app.UseSwaggerAuthorized( );
app.UseSwagger( );
app.UseSwaggerUI( c => c.SwaggerEndpoint( "/swagger/v1/swagger.json", "Broker.Rest v1" ) );
I think Chrome can not excute the "UseSwaggerAuthorized". I test it in many ways.
This is my UseSwaggerAuthorized method
public static class AuthorizedSampleClass
{
public static IApplicationBuilder UseSwaggerAuthorized( this IApplicationBuilder builder )
{
return builder.UseMiddleware<SwaggerBasicAuthMiddleware>( );
}
}
public class SwaggerBasicAuthMiddleware
{
private readonly RequestDelegate next;
public SwaggerBasicAuthMiddleware( RequestDelegate next )
{
this.next = next;
}
public async Task InvokeAsync( HttpContext context )
{
if ( context.Request.Path.StartsWithSegments( "/swagger" ) )
{
string authHeader = context.Request.Headers[ "Authorization" ];
if ( authHeader != null && authHeader.StartsWith( "Basic " ) )
{
// Get the credentials from request header
var header = AuthenticationHeaderValue.Parse( authHeader );
var inBytes = Convert.FromBase64String( header.Parameter );
var credentials = Encoding.UTF8.GetString( inBytes ).Split( ':' );
var username = credentials[ 0 ];
var password = credentials[ 1 ];
// validate credentials
if ( username.Equals( "a" ) && password.Equals( "a" ) )
{
await next.Invoke( context ).ConfigureAwait( false );
return;
}
}
context.Response.Headers[ "WWW-Authenticate" ] = "Basic";
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
await next.Invoke( context ).ConfigureAwait( false );
}
}
}
Chrome update, chrome bug, startup.cs settings, Lunchsetting.json, appsetting.json

while using cookies in Xunit Selenium C# Got System.NullReferenceException : Object reference not set to an instance of an object Error

[Theory]
[InlineData(BrowserType.Chrome)]
[InlineData(BrowserType.Firefox)]
public void GetCookies(BrowserType browserType)
{
using (var driver = WebDriverInfra.Create_Browser(browserType))
{
driver.Manage().Cookies.DeleteAllCookies();
TestOutputHelper.WriteLine("Login is started.");
Wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl(LoginUrl);
driver.FindElement(By.Id("username")).SendKeys(Username);
driver.FindElement(By.Id("password")).SendKeys(Password);
driver.FindElement(By.ClassName("submit")).Click();
string welcomeSign = Wait.Until<string>(driver => driver.FindElement(By.XPath("/html/body/div[1]/div[2]/div[2]/div/div[1]/div/div/div/div[1]/h2")).Text);
welcomeSign.Should().NotBeNull();
welcomeSign.Should().Contain("Welcome");
var userFirstNameCookie = Driver.Manage().Cookies.GetCookieNamed("userFirstName")
userFirstNameCookie.Value.Should().Be(FirstName);
TestOutputHelper.WriteLine("login is completed.");
webDriverInfra.CS
public static IWebDriver Create_Browser(BrowserType browserType)
{
switch (browserType)
{
case BrowserType.Chrome:
return new ChromeDriver();
case BrowserType.Firefox:
return new FirefoxDriver();
default:
throw new ArgumentOutOfRangeException(nameof(browserType), browserType, null);
}
}
Browsertype.CS
public enum BrowserType
{
NotSet,
Chrome,
Firefox,
}
Can anyone help me on this to get rid of the null reference exception. This is my whole code. My test is passing till login when it hits the cookie line the null exception appears.

google authentication stuck when redirecting back to my website

so i use google authentication to validate the users on our system
here is my code
public IActionResult Login()
{
System.IO.File.WriteAllText("log.txt", Url.Action("ExternalLoginCallback"));
return new ChallengeResult(
GoogleDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = Url.Action("ExternalLoginCallback")
});
}
public IActionResult ExternalLoginCallback()
{
System.IO.File.AppendAllText("log.txt", "I am redirected");
var authenticateResult = HttpContext.AuthenticateAsync("External").Result;
if (!authenticateResult.Succeeded)
return BadRequest(); // TODO: Handle this better.
var claimsIdentity = new ClaimsIdentity("Application");
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier));
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.Email));
var identity = authenticateResult.Principal.Identities.FirstOrDefault();
if (identity != null)
{
var emailClaim = identity.Claims.FirstOrDefault(c => c.Type.ToLower().Contains("emailaddress"));
if (emailClaim == null)
{
return BadRequest();
}
var emailData = emailClaim.Value;
if (string.IsNullOrEmpty(emailData))
{
return BadRequest();
}
var connectionString = _config.GetConnectionString("DefaultConnection");
UserBL userBL = new UserBL(connectionString);
var userModel = userBL.GetUserData(emailData);
if(userModel == null || userModel.HasError)
{
return BadRequest();
}
HttpContext.Session.SetString("UserData", JsonConvert.SerializeObject(userModel.Data));
if (userModel.Data.UserRoles.Any(r => r.Id == (int)UserRolesEnum.ProductOwner
|| r.Id == (int)UserRolesEnum.CopyEditor))
{
return RedirectToAction("Index", "Home");
}
else
{
return RedirectToAction("List", "Translation");
}
return RedirectToAction("UnAuthorized");
}
return BadRequest();
}
it worked fine users were redirected to google to enter their credentials and after that google redirects them back to the website till couple of days back google stopped redirecting back to the website and stays stuck on https://accounts.google.com.eg/accounts/SetSID
any pointers to how i can debug this or how to solve it
any help would be appreciated
Finally after a week i found the problem, it was not in the code it was the server.
The IIS limits the query string character count (i think the default is 260 character) and in my case google responds with a query string with 544 character in which the IIS does not accept or respond to so it stays stuck on the SetSID page
Here is where i found the solution to increase the query string max length
Increase max url length in asp.net core
as of why it was working and then stopped this i could not figure it out

Selenium: cookie functionality not working

I am new to selenium. I am trying to test an application. Application has two pages login.jsp, restricted.jsp. You can access restricted.jsp, only after login (trying to access restricted.jsp without login will redirect to login.jsp page). My selenium application is like below.
a. Login to the app first
b. After successful login, store all the cookies to "session.properties" file.
c. Next time onwards, I am loading all the cookies from "session.properties" to driver and try to access "restricted.jsp" page. But I am redirecting to login.jsp, instead of restricted.jsp.
Following is my Java code.
public class App {
private static void loginApp(WebDriver driver) {
driver.get("http://localhost:8080/selenium_app/login");
WebElement userName = driver.findElement(By.name("userName"));
WebElement password = driver.findElement(By.name("password"));
userName.sendKeys("admin");
password.sendKeys("admin");
userName.submit();
}
private static void storeSessionProps(WebDriver driver) throws IOException {
File f = new File("session.properties");
f.delete();
f.createNewFile();
FileWriter fos = new FileWriter(f);
BufferedWriter bos = new BufferedWriter(fos);
/* Get all the cookies and store them to session.properties file */
Set<Cookie> cookies = driver.manage().getCookies();
for (Cookie cookie : cookies) {
bos.write(cookie.getName() + "=" + cookie.getValue());
bos.newLine();
}
bos.flush();
bos.close();
fos.close();
}
private static void loadPropertiesToDriver(WebDriver driver)
throws IOException {
Properties properties = new Properties();
FileInputStream fin = new FileInputStream("session.properties");
properties.load(fin);
Set<Object> props = properties.keySet();
for (Object prop : props) {
Cookie ck = new Cookie((String) prop,
properties.getProperty((String) prop));
driver.manage().addCookie(ck);
System.out.println(ck);
}
}
public static void main(String[] args) throws InterruptedException,
IOException {
WebDriver driver = new FirefoxDriver();
// loginApp(driver);
// storeSessionProps(driver);
loadPropertiesToDriver(driver);
driver.get("http://localhost:8080/selenium_app/restricted");
Thread.sleep(5000);
driver.quit();
}
}
When I uncomment the lines loginApp(driver);, storeSessionProps(driver); everything is fine, I am able to access restricted.jsp page, but when I ran application by commenting those and loading the cookies, I am redirecting to login.jsp page. Any help on this??
You need to store all the data from your cookies, not just the names/values. Moreover, before creating a cookie, your need to load a page with a domain that will match the domain of the cookie.
This is an example to quickly store and restore the cookies:
Path cookiesFile = Paths.get("C:\\Temp\\cookies.txt");
WebDriver driver = new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
// load the domain
driver.get("https://www.google.com");
if(cookiesFile.toFile().exists()) {
// load the cookies into the browser for the current domain
String cookies = new String(Files.readAllBytes(cookiesFile), Charsets.UTF_8);
js.executeScript(cookies);
// reload the page with the injected cookies
driver.get("https://www.google.com");
}
// save the cookies to a file for the current domain
try(PrintWriter file = new PrintWriter(cookiesFile.toFile(), "UTF-8")){
for(Cookie c : driver.manage().getCookies()) {
file.println("document.cookie='" + c.toString() + "';");
}
}