HTTP Basic Authentication with UnityWebRequest

Use data from secured endpoints in custom Editor tools

Cover image
by Tommy Leung on February 16th, 2020

Do you need to make a web request to a secured endpoint from an internal Editor tool in Unity?

Maybe you want to make it easier to track down bugs that are specific to player data?

Or you need some internal data in order to generate files for your game.

The data is secured with Basic Authentication so that sensitive data can't be accessed publicly by whoever has the URL.

This is fairly easy to do with UnityWebRequest. Game development and web development have non-overlapping domains of knowledge so how to do it may not be obvious.

Setting Authorization Headers

You'll need to add an Authorization header to your UnityWebRequest with a value of Basic {Base64(username:password)}.

Where the second half in curly braces will be the base64 encoded value of the username and password joined by a colon :.

If your username was shigeru and password was miyamoto then you would base64 encode shigeru:miyamoto which is c2hpZ2VydTptaXlhbW90bw==.

The code would look like this:

UnityWebRequest createRequest(string url, string username, string password)
{
	UnityWebRequest req = UnityWebRequest.Get(url);

	// could also use "US-ASCII" or "ISO-8859-1" encoding
	string encoding = "UTF-8"; 
	string base64 = System.Convert.ToBase64String(
		System.Text.Encoding.GetEncoding(encoding)
			.GetBytes(username + ":" + password)
	);

	req.SetRequestHeader("Authorization", "Basic " + base64);
	
	return req;
}

Notice that we are suggesting UTF-8 encoding. The latest official specification requires a US-ASCII compatible encoding like UTF-8. You can use US-ASCII if you prefer.

The ISO-8859-1 option is for the obsolete specification. If you get an HTTP/1.1 401 Unauthorized error back from the server and you are sure your credentials are correct then it wouldn't hurt to give this encoding a try.

You can check for errors by logging error when isHttpError is true on your UnityWebRequest.

UnityWebRequest req = this.createRequest(url, "shigeru", "miyamoto");

yield return req.SendWebRequest();

if (req.isNetworkError || req.isHttpError)
{
	Debug.LogError(req.error);
}

Or with async/await and the UniTask library:

UnityWebRequest req = await this.createRequest(url, "shigeru", "miyamoto")
	.SendWebRequest();

if (req.isNetworkError || req.isHttpError)
{
	Debug.LogError(res.error);
}

That's how you use Basic Authentication with UnityWebRequest. The trickiest part was simply knowing the formatting and encoding!

Don't miss the next Unity technique! Enter your email into the box below to subscribe.