Search code examples
c#visual-studioseleniumselenium-chromedriverbasic-authentication

How to manage Basic Authentication login with selenium c#?


I'm making tests for the company where i'm doing my intership, but i don't know how to make that the script put my credentials in this part, if i enter in the page(myself, not the chromedriver) automatically gets the credentials from the login on my pc, obviously the test driver can't do that, that's why i get that alert, my question is how can i put the credentials there automatically? for now i'm putting a thread sleep and putting the credentials manually but i know that's not the optimal way to do it, i already try using the alert methods:

var alert = driver.SwitchTo().Alert();
alert.SetAuthenticationCredentials("user","password");
alert.Accept();

But I get this error:

Message: OpenQA.Selenium.NoAlertPresentException : no such alert
(Session info: chrome=87.0.4280.141)

And if i put a wait i got a timeout but nothing happen, as you can see i'm using chrome, i read a post from some years that chrome can't manage alerts, but i don't know if that's a thing today, i hope you guys can help me.


Solution

  • After days on research and trying, this is what works for me, i did a Google Chrome extension, the basic authentication method of http://user:password@mywebsite.com don't work anymore so i did this extension with my credentials, it's kinda risky but it was the only solution that i found

    First you need to make a manifest.json:

    {
      "name": "Webrequest API",
      "version": "1.0",
      "description": "Extension to handle Authentication window",
      "permissions": [
        "webRequest",
        "webRequestBlocking",
        "<all_urls>"
      ],
      "background": {
        "scripts": [
          "webrequest.js"
        ]
      },
      "manifest_version": 2
    }
    

    Then you need to create webrequest.js:

    chrome.webRequest.onAuthRequired.addListener(function(details){
            console.log("chrome.webRequest.onAuthRequired event has fired");
            return {
                    authCredentials: {username: "myusername", password: "mypassword"}
                };
        },
        {urls:["<all_urls>"]},
        ['blocking']);
    

    After that you need to create the crx, in the chrome://Extension site in developer mode, after that you should login without problem in the website you're trying to login.

    References: How to handle authentication popup in Chrome with Selenium WebDriver using Java

    I hope help to anyone who come to this post