Is there a way to pass JWT Token for Auth into Selenium WebDriver in C# Asp.net Core?

2.5k views Asked by At

I need a way to Authenticate myself on my WebAPI Automation. I have extracted the bearer token and passed my json into a .net object , how do I pass in the JWT / Bearer Token & inject the needed headers into a ChromeDriver Session when it opens so when my app navigates to https://localhost:5000/login it should automatically redirect to -> https://localhost:5000/Dashboard.

class Program
{

    //private static IWebDriver driver;

    // ******->Selenium Specific Code<-******
    // Instantiate the Chrome Driver
    var driver = new ChromeDriver("/usr/local/bin/");

    static IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor;

    public static string setItemInLocalStorage(string item, string value)
    {


        var js = ((IJavaScriptExecutor)driver).ExecuteScript(String.Format(
         "window.localStorage.setItem('userDetails','" + value + "');"));

        return "";

    }

    //Method to Authenticate & GET Bearer Token from API.

    public static async void GetAllWorkshopData(int WorkshopId)
    {
        UserAuth ua = new UserAuth();
        ua.EmailAddress = "[email protected]";
        ua.Password = "Strongest!!!Pwd";
        ua.WorkshopId = WorkshopId;

        using (var client = new HttpClient())
        {

            var uri = "https://localhost:5001/api/userauth/Login";
            string json = JsonConvert.SerializeObject(ua);
            StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
            var res = await client.PostAsync(uri, content);
            string datar = await res.Content.ReadAsStringAsync();

            Example details = JsonConvert.DeserializeObject<Example>(datar);



            
            // Navigate to the Endpoint
            ///here inject basic-auth token before selenium opens browser

            driver.Navigate().GoToUrl("http://localhost:5000/Login");
          

            setItemInLocalStorage("", datar);

            driver.Navigate().GoToUrl("http://localhost:5000/Dashboard");
        } 
1

There are 1 answers

0
vikas On

You can use javascript executors here. Following is an example you can use to set your session, cookies etc

 IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
                    
 driver.Navigate().GoToUrl("http://localhost:5000/Login");

 js.ExecuteScript("window.sessionStorage.setItem('token', 'your access token')");