How to pass Auth in a "get" request using urllib.request Python - TagMerge
3How to pass Auth in a "get" request using urllib.request PythonHow to pass Auth in a "get" request using urllib.request Python

How to pass Auth in a "get" request using urllib.request Python

Asked 1 years ago
0
3 answers

I tried using requests module which work perfectly but I am trying to learn about urllib.request module so that is why.

from requests.auth import HTTPBasicAuth
import requests
r=requests.get('http://httpbin.org/basic-auth/ali/pass', auth=HTTPBasicAuth('ali', 'pass'))
print(r.status_code)

Source: link

0

When using OAuth or other authentication services you can often also send your access token in a query string instead of in an authorization header, so something like:
GET https://www.example.com/api/v1/users/1?access_token=1234567890abcdefghijklmnopqrstuvwxyzABCD

Source: link

0

Java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Base64;


// HTTP basic authentication example in Java using the RTC Server RESTful API
public class Base64Encoding {

    public static void main(String[] args) throws IOException, InterruptedException {

        // Customer ID
        final String customerKey = "Your customer ID";
        // Customer secret
        final String customerSecret = "Your customer secret";

        // Concatenate customer key and customer secret and use base64 to encode the concatenated string
        String plainCredentials = customerKey + ":" + customerSecret;
        String base64Credentials = new String(Base64.getEncoder().encode(plainCredentials.getBytes()));
        // Create authorization header
        String authorizationHeader = "Basic " + base64Credentials;

        HttpClient client = HttpClient.newHttpClient();

        // Create HTTP request object
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.agora.io/dev/v1/projects"))
                .GET()
                .header("Authorization", authorizationHeader)
                .header("Content-Type", "application/json")
                .build();
        // Send HTTP request
        HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
Golang
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
  "encoding/base64"
)

// HTTP basic authentication example in Golang using the RTC Server RESTful API
func main() {

  // Customer ID
  customerKey := "Your customer ID"
  // Customer secret
  customerSecret := "Your customer secret"

  // Concatenate customer key and customer secret and use base64 to encode the concatenated string
  plainCredentials := customerKey + ":" + customerSecret
  base64Credentials := base64.StdEncoding.EncodeToString([]byte(plainCredentials))

  url := "https://api.agora.io/dev/v1/projects"
  method := "GET"

  payload := strings.NewReader(``)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  // Add Authorization header
  req.Header.Add("Authorization", "Basic " + base64Credentials)
  req.Header.Add("Content-Type", "application/json")

  // Send HTTP request
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
PHP
<?php
// HTTP basic authentication example in PHP using the RTC Server RESTful API
// Customer ID
$customerKey = "Your customer ID";
// Customer secret
$customerSecret = "Your customer secret";
// Concatenate customer key and customer secret
$credentials = $customerKey . ":" . $customerSecret;

// Encode with base64
$base64Credentials = base64_encode($credentials);
// Create authorization header
$arr_header = "Authorization: Basic " . $base64Credentials;

$curl = curl_init();
// Send HTTP request
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://api.agora.io/dev/v1/projects',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',

  CURLOPT_HTTPHEADER => array(
    $arr_header,
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

if($response === false) {
    echo "Error in cURL : " . curl_error($curl);
}

curl_close($curl);

echo $response;
C#
using System;
using System.IO;
using System.Net;
using System.Text;

// HTTP basic authentication example in C# using the RTC Server RESTful API
namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Customer ID
            string customerKey = "Your customer ID";
            // Customer secret
            string customerSecret = "Your customer secret";
            // Concatenate customer key and customer secret and use base64 to encode the concatenated string
            string plainCredential = customerKey + ":" + customerSecret;

            // Encode with base64
            var plainTextBytes = Encoding.UTF8.GetBytes(plainCredential);
            string encodedCredential = Convert.ToBase64String(plainTextBytes);
            // Create authorization header
            string authorizationHeader = "Authorization: Basic " + encodedCredential;

            // Create request object
            WebRequest request = WebRequest.Create("https://api.agora.io/dev/v1/projects");
            request.Method = "GET";

            // Add authorization header
            request.Headers.Add(authorizationHeader);
            request.ContentType = "application/json";

            WebResponse response = request.GetResponse();
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(dataStream);
                string responseFromServer = reader.ReadToEnd();
                Console.WriteLine(responseFromServer);
            }

            response.Close();
        }
    }
}
node.js
// HTTP basic authentication example in node.js using the RTC Server RESTful API
const https = require('https')
// Customer ID
const customerKey = "Your customer ID"
// Customer secret
const customerSecret = "Your customer secret"
// Concatenate customer key and customer secret and use base64 to encode the concatenated string
const plainCredential = customerKey + ":" + customerSecret
// Encode with base64
encodedCredential = Buffer.from(plainCredential).toString('base64')
authorizationField = "Basic " + encodedCredential


// Set request parameters
const options = {
  hostname: 'api.agora.io',
  port: 443,
  path: '/dev/v1/projects',
  method: 'GET',
  headers: {
    'Authorization':authorizationField,
    'Content-Type': 'application/json'
  }
}

// Create request object and send request
const req = https.request(options, res => {
  console.log(`Status code: ${res.statusCode}`)

  res.on('data', d => {
    process.stdout.write(d)
  })
})

req.on('error', error => {
  console.error(error)
})

req.end()

Source: link

Recent Questions on python

    Programming Languages