HTTPS/Authenticated: Difference between revisions

m
→‎{{header|Wren}}: Another minor change
(Added Wren)
m (→‎{{header|Wren}}: Another minor change)
 
(9 intermediate revisions by 7 users not shown)
Line 3:
The goal of this task is to demonstrate [[HTTPS request]]s with authentication.
Implementations of this task should not use client certificates for this: that is the subject of [[Client-Authenticated HTTPS Request|another task]].
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">user: "admin"
pass: "admin"
 
inspect request.headers:#[
Authorization: "Basic " ++ encode user ++ ":" ++ pass
] "https://httpbin.org/basic-auth/admin/admin" ø</syntaxhighlight>
 
{{out}}
 
<pre>[ :dictionary
version : 1.1 :string
body : {
"authenticated": true,
"user": "admin"
}
:string
headers : [ :dictionary
server : gunicorn/19.9.0 :string
content-length : 48 :integer
access-control-allow-credentials : true :logical
content-type : application/json :string
date : [ :date
hour : 15 :integer
minute : 14 :integer
second : 57 :integer
nanosecond : 0 :integer
day : 20 :integer
Day : Tuesday :string
days : 353 :integer
month : 12 :integer
Month : December :string
year : 2022 :integer
utc : -3600 :integer
]
access-control-allow-origin : * :string
connection : keep-alive :string
]
status : 200 :integer
]</pre>
 
=={{header|AutoHotkey}}==
{{libheader|iweb}}
{{libheader|COM}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">iWeb_Init()
pwb := iWeb_newGui(0, 0, 1000, 800)
iWeb_nav(pwb, "http://www.facebook.com/login.php?ref=pf")
Line 21 ⟶ 63:
#Include iweb.ahk
#Include COM.ahk
#Include COMinvokeDeep.ahk</langsyntaxhighlight>
 
=={{header|BaCon}}==
<langsyntaxhighlight lang="bacon">OPTION TLS TRUE
 
website$ = "website.com"
Line 40 ⟶ 82:
CLOSE NETWORK conn
 
PRINT total$</langsyntaxhighlight>
 
=={{header|C}}==
{{libheader|libcurl}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include "curl/curl.h"
Line 65 ⟶ 107:
}
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|3.0}}
 
<langsyntaxhighlight lang="csharp">
using System;
using System.Net;
Line 90 ⟶ 132:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
{{libheader|clj-http}}
 
<langsyntaxhighlight lang="clojure">(clj-http.client/get "https://somedomain.com"
{:basic-auth ["user" "pass"]})</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program ShowHTTPSAuthenticated;
 
{$APPTYPE CONSOLE}
Line 124 ⟶ 166:
lIOHandler.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Go}}==
The task solution is really the client program, but to test it I wrote a server and created a custom certificate. I won't describe the certificate, but this is the server:
<langsyntaxhighlight lang="go">package main
 
import (
Line 165 ⟶ 207:
http.HandleFunc("/", hw)
log.Fatal(http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", nil))
}</langsyntaxhighlight>
It is a "Hello world" server, but over TLS and with basic authentication required on the Get. Errors are logged to aid client debugging.
 
The client:
<langsyntaxhighlight lang="go">package main
 
import (
Line 217 ⟶ 259:
}
fmt.Println(string(b))
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 223 ⟶ 265:
Example uses the [https://hackage.haskell.org/package/req <tt>req</tt>] and [https://hackage.haskell.org/package/aeson <tt>aeson</tt>] packages:
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE OverloadedStrings #-}
 
module Main (main) where
Line 249 ⟶ 291:
jsonResponse
(basicAuth "someuser" "somepassword")
print (responseBody response :: Value)</langsyntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
 
public final class HTTPSAuthenticated {
 
public static void main(String[] aArgs) throws IOException, InterruptedException, URISyntaxException {
HttpClient client = HttpClient.newBuilder()
.authenticator( new MyAuthenticator() )
.build();
 
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri( new URI("https://postman-echo.com/basic-auth") ) // This website requires authentication
.build();
 
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
System.out.println("Status: " + response.statusCode());
}
 
}
 
final class MyAuthenticator extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String username = "kingkong";
String password = "test1234";
return new PasswordAuthentication(username, password.toCharArray());
}
}
</syntaxhighlight>
{{ out }}
<pre>
Status: 200
</pre>
 
=={{header|Julia}}==
An example using HTTP (see the source for HTTP.jl for the code below ) to access and play a song:
<syntaxhighlight lang="julia">
<lang Julia>
using HTTP, HTTP.IOExtras, JSON, MusicProcessing
HTTP.open("POST", "http://music.com/play") do io
Line 267 ⟶ 356:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.2.0
 
import java.net.Authenticator
Line 297 ⟶ 386:
println(line)
}
}</langsyntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(username = 'hello',password = 'world')
local(x = curl('https://sourceforge.net'))
#x->set(CURLOPT_USERPWD, #username + ':' + #password)
local(y = #x->result)
#y->asString</langsyntaxhighlight>
 
=={{header|LiveCode}}==
HTTP Basic Auth as part of url
<langsyntaxhighlight LiveCodelang="livecode">command getAuthWebResource
libURLFollowHttpRedirects true
libURLSetSSLVerification true
put URL "https://user:passwd@example.basicauth.com/" into response
put response
end getAuthWebResource</langsyntaxhighlight>
 
You can also set the headers for the basic auth requests
<langsyntaxhighlight LiveCodelang="livecode">command getAuthWebResource
libURLFollowHttpRedirects true
libURLSetSSLVerification true
Line 322 ⟶ 411:
put URL "https://example.basicauth.com" into response
put response
end getAuthWebResource</langsyntaxhighlight>
 
=={{header|Lua}}==
Line 328 ⟶ 417:
{{libheader|lua-requests}}
 
<langsyntaxhighlight lang="lua">
local requests = require('requests')
local auth = requests.HTTPBasicAuth('admin', 'admin')
Line 336 ⟶ 425:
})
io.write(string.format('Status: %d', resp.status_code))
</syntaxhighlight>
</lang>
 
{{out}}
Line 342 ⟶ 431:
Status: 200
</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">a = RunThrough["curl -u JohnDoe:Password https://www.example.com", 1]
For[ i=0, i < Length[a] , i++, SomeFunction[a]]</syntaxhighlight>
 
=={{header|Nim}}==
{{libheader|OpenSSL}}
 
Compile with command <code>nim c -d:ssl https_authenticated.nim</code>.
<lang Nim>import httpclient, base64
 
<syntaxhighlight lang="nim">import httpclient, base64
 
const
Line 354 ⟶ 449:
let headers = newHttpHeaders({"Authorization": "Basic " & base64.encode(User & ":" & Password)})
let client = newHttpClient(headers = headers)
echo client.getContent("https://httpbin.org/basic-auth/admin/admin")</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a = RunThrough["curl -u JohnDoe:Password https://www.example.com", 1]
For[ i=0, i < Length[a] , i++, SomeFunction[a]]</lang>
 
=={{header|Perl}}==
{{libheader|LWP}}
<langsyntaxhighlight lang="perl">use LWP::UserAgent qw();
my $ua = LWP::UserAgent->new;
my $netloc = 'http://www.buddhism-dict.net/cgi-bin/xpr-dealt.pl:80';
Line 380 ⟶ 471:
passwd => 'YYYYYY',
'.persistent' => 'y', # tick checkbox
});</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 386 ⟶ 477:
Exactly the same as the [[HTTP#Phix]] task.
You can of course use curl_easy_setopt(curl,CURLOPT_USERPWD,"user:password") rather than embed that in the url.
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang Phix>include builtins\libcurl.e
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span>
curl_global_init()
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">libcurl</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
atom curl = curl_easy_init()
<span style="color: #7060A8;">curl_global_init</span><span style="color: #0000FF;">()</span>
curl_easy_setopt(curl, CURLOPT_URL, "https://user:password@example.com/")
<span style="color: #004080;">atom</span> <span style="color: #000000;">curl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_init</span><span style="color: #0000FF;">()</span>
object res = curl_easy_perform_ex(curl)
<span style="color: #7060A8;">curl_easy_setopt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CURLOPT_URL</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"https://user:password@example.com/"</span><span style="color: #0000FF;">)</span>
curl_easy_cleanup(curl)
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">curl_easy_perform_ex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
curl_global_cleanup()
<span style="color: #7060A8;">curl_easy_cleanup</span><span style="color: #0000FF;">(</span><span style="color: #000000;">curl</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">curl_global_cleanup</span><span style="color: #0000FF;">()</span>
puts(1,res)</lang>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let (User "Bill" Pass "T0p5ecRet" Url "https://www.example.com")
(in (list 'curl "-u" (pack User ': Pass) Url)
(while (line)
(doSomeProcessingWithLine @) ) ) )</langsyntaxhighlight>
=={{header|PowerShell}}==
{{trans|C#}}
<langsyntaxhighlight PowerShelllang="powershell">$client = [Net.WebClient]::new()
# credentials of current user:
$client.Credentials = [Net.CredentialCache]::DefaultCredentials
Line 409 ⟶ 503:
# $client.Credentials = [System.Net.NetworkCredential]::new("User", "Password")
$data = $client.DownloadString("https://example.com")
Write-Host $data</langsyntaxhighlight>
=={{header|Python}}==
{{works with|Python|2.4 and 2.6}}
Line 415 ⟶ 509:
'''Note:''' You should install '''''mechanize''''' to run code below. Visit: http://wwwsearch.sourceforge.net/mechanize/
 
<langsyntaxhighlight lang="python">#!/usr/bin/python
# -*- coding: utf-8 -*-
 
Line 438 ⟶ 532:
 
response = br.submit()
print response.read()</langsyntaxhighlight>
 
{{libheader|Requests}}
{{works with|Python|2.7, 3.4–3.7}}
<langsyntaxhighlight lang="python">import requests
 
username = "user"
Line 450 ⟶ 544:
response = requests.get(url, auth=(username, password)
 
print(response.text)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 474 ⟶ 568:
(for ([l (in-port read-line (get-pure-port (string->url "https://www.google.com/")))])
(displayln l))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 481 ⟶ 575:
Used here to connect to my local wireless router to a page that is password protected. Obviously not going to be generally publicly accessible but should be easily adaptable to other sites / devices.
 
<syntaxhighlight lang="raku" perl6line>use HTTP::UserAgent;
 
my $username = 'username'; # my username
Line 490 ⟶ 584:
$ua.auth( $username, $password );
my $response = $ua.get: $address;
say $response.is-success ?? $response.content !! $response.status-line;</langsyntaxhighlight>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'uri'
require 'net/http'
 
Line 501 ⟶ 595:
request.basic_auth('username', 'password')
http.request request
end</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">html "
<CENTER><TABLE CELLPADDING=0 CELLSPACING=0 border=1 bgcolor=wheat>
<TR><TD colspan=2 bgcolor=tan align=center>LOGIN</TD></TR>
Line 535 ⟶ 629:
 
[exit]
end</langsyntaxhighlight>
[[File:ClientAuthorizationRunBasic.png]]
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
extern crate reqwest;
 
Line 560 ⟶ 654:
println!("{}", body);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 567 ⟶ 661:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.net.{Authenticator, PasswordAuthentication, URL}
 
import javax.net.ssl.HttpsURLConnection
Line 590 ⟶ 684:
new BufferedSource(con.getInputStream).getLines.foreach(println(_))
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">require('WWW::Mechanize')
 
var mech = %s'WWW::Mechanize'.new(
Line 606 ⟶ 700:
'login' => 'XXXXXX',
'passwd' => 'YYYYYY',
))</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 612 ⟶ 706:
{{tcllib|base64}}
Uses the [http://tls.sourceforge.net Tls] package.
<langsyntaxhighlight Tcllang="tcl">package require http
package require tls
http::register https 443 ::tls::socket
Line 626 ⟶ 720:
# Now as for conventional use of the “http” package
set data [http::data $token]
http::cleanup $token</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
Line 635 ⟶ 729:
{{works with|VBA|6.5}}
{{works with|VBA|7.1}}
<langsyntaxhighlight lang="vb">Sub Main()
' in the "references" dialog of the IDE, check
' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll)
Line 656 ⟶ 750:
HttpReq.Send
Debug.Print HttpReq.ResponseText
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 662 ⟶ 756:
{{libheader|libcurl}}
An embedded program so we can ask the C host to communicate with libcurl for us.
<langsyntaxhighlight ecmascriptlang="wren">/* https_authenticatedHTTPS_Authenticated.wren */
 
var CURLOPT_URL = 10002
Line 692 ⟶ 786:
return
}
curl.easyCleanup()</langsyntaxhighlight>
<br>
We now embed this in the following C program, compile and run it.
<langsyntaxhighlight lang="c">/* gcc https_authenticatedHTTPS_Authenticated.c -o https_authenticatedHTTPS_Authenticated -lcurl -lwren -lm */
 
#include <stdio.h>
Line 805 ⟶ 899:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "https_authenticatedHTTPS_Authenticated.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 821 ⟶ 915:
free(script);
return 0;
}</langsyntaxhighlight>
 
=={{header|zkl}}==
Using cURL to do the heavy lifting, get a XML list of computers connected to my router.
<langsyntaxhighlight lang="zkl">zkl: var ZC=Import("zklCurl")
zkl: var data=ZC().get("http://usr:pw@192.168.1.1/computer_list.xml")
L(Data(1,049),121,0)
zkl: data[0][121,*].text</langsyntaxhighlight>
{{out}}
<pre>
Line 840 ⟶ 934:
{{omit from|Brainf***}}
{{omit from|Commodore BASIC|Does not have network access}}
{{omit from|EasyLang|Has no internet functions}}
{{omit from|Inform 7|Does not have network access.}}
{{omit from|Locomotive Basic|Does not have network access.}}
9,482

edits