b2_get_download_authorization

Used to generate an authorization token that can be used to download files with the specified prefix (and other optional headers) from a private B2 bucket. Returns an authorization token that can be passed to b2_download_file_by_name in the Authorization header or as an Authorization parameter.

Request HTTP Headers

Authorization

required

The account authorization token returned by b2_authorize_account. The token must have the shareFiles capability.

Request HTTP Message Body Parameters

bucketId

required

The identifier for the bucket.

fileNamePrefix

required

The file name prefix of files the download authorization token will allow b2_download_file_by_name to access. For example, if you have a private bucket named "photos" and generate a download authorization token for the fileNamePrefix "pets/" you will be able to use the download authorization token to access: https://f345.backblazeb2.com/file/photos/pets/kitten.jpg but not: https://f345.backblazeb2.com/file/photos/vacation.jpg.

validDurationInSeconds

required

The number of seconds before the authorization token will expire. The minimum value is 1 second. The maximum value is 604800 which is one week in seconds.

b2ContentDisposition

optional

If this is present, download requests using the returned authorization must include the same value for b2ContentDisposition. The value must match the grammar specified in RFC 6266 (except that parameter names that contain an '*' are not allowed).

Response

Response HTTP Status 200

Authorization succeeded. The JSON response will contain:

bucketId

The identifier for the bucket.

fileNamePrefix

The prefix for files the authorization token will allow b2_download_file_by_name to access.

authorizationToken

The authorization token that can be passed in the Authorization header or as an Authorization parameter to b2_download_file_by_name to access files beginning with the file name prefix.

Response Errors

Authorization Failed. If possible the server will return a JSON error structure. Errors include:

status

code

description

400

bad_request

The request had the wrong fields or illegal values. The message returned with the error will describe the problem.

401

unauthorized

The auth token used is valid, but does not authorize this call with these parameters. The capabilities of an auth token are determined by the application key used with b2_authorize_account.

401

bad_auth_token

The auth token used is not valid. Call b2_authorize_account again to either get a new one, or an error message describing the problem.

401

expired_auth_token

The auth token used has expired. Call b2_authorize_account again to get a new one.

503

service_unavailable

<various>

API Versions

v1: Application keys (July 26, 2018)

Incompatible change: After calling b2_authorize_account with an application key that does not have the right permissions, this call will return a 401 Unauthorized.

v1: Original release (September 22, 2015)

Sample Code

Code

BUCKET_ID=... # The ID of the bucket you want to authorize
FILE_NAME_PREFIX=... # The file name prefix of files the download authorization will allow
VALID_DURATION=... # The number of seconds the authorization is valid for
ACCOUNT_AUTHORIZATION_TOKEN = "" # Provided by b2_authorize_account

curl -H 'Authorization: $ACCOUNT_AUTHORIZATION_TOKEN' \
     -D '{"bucketId":"$BUCKET_ID","fileNamePrefix":"$FILE_NAME_PREFIX","validDurationInSeconds":$VALID_DURATION}' \
     https://apiNNN.backblazeb2.com/b2api/v2/b2_get_download_authorization

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

import java.io.*;
import java.util.*;
import javax.json.*;
import java.net.HttpURLConnection;
import java.net.URL;

String apiUrl = ""; // Provided by b2_authorize_account
String bucketId = ""; // The bucket that files can be downloaded from
String fileNamePrefix = "" ; // The file name prefix of files the download authorization will allow
int validDuration = 86400; // The number of seconds the authorization is valid for
String accountAuthorizationToken = ""; // Provided by b2_authorize_account
HttpURLConnection connection = null;
String postParams = "{\"bucketId\":\"" + bucketId + "\", \"fileNamePrefix\":\"" + fileNamePrefix + "\", \"validDurationInSeconds\":"+ validDuration +"}";
byte postData[] = postParams.getBytes(StandardCharsets.UTF_8);
try {
    URL url = new URL(apiUrl + "/b2api/v2/b2_get_download_authorization");
    connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", accountAuthorizationToken);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");
    connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
    connection.setDoOutput(true);
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
    writer.write(postData);
    String jsonResponse = myInputStreamReader(connection.getInputStream());
    System.out.println(jsonResponse);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    connection.disconnect();
}

static public String myInputStreamReader(InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in);
    StringBuilder sb = new StringBuilder();
    int c = reader.read();
    while (c != -1) {
        sb.append((char)c);
        c = reader.read();
    }
    reader.close();
    return sb.toString();
}

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

import json
import urllib2

api_url = "" # Provided by b2_authorize_account
bucket_id = "" # The bucket that files can be downloaded from
file_name_prefix = "" # The file name prefix of files the download authorization will allow
valid_duration = 86400 # The number of seconds the authorization is valid for
account_authorization_token = "" # Provided by b2_authorize_account
request = urllib2.Request(
    '%s/b2api/v2/b2_get_download_authorization' % api_url,
    json.dumps({ 'bucketId' : bucket_id, 'fileNamePrefix' : file_name_prefix, 'validDurationInSeconds' : valid_duration}),
    headers = { 'Authorization': account_authorization_token }
    )
response = urllib2.urlopen(request)
response_data = json.loads(response.read())
response.close()

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

import Foundation

let apiUrl = "" // Provided by b2_authorize_account
let bucketId = "" // The bucket that files can be downloaded from
let fileNamePrefix = "" // The file name prefix of files the download authorization will allow
let validDuration = 86400 // The number of seconds the authorization is valid for
let accountAuthorizationToken = "" // Provided by b2_authorize_account

// Create the request
var request = URLRequest(url: URL(string: "\(apiUrl)/b2api/v2/b2_get_download_authorization")!)
request.httpMethod = "POST"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
request.httpBody = "{\"bucketId\":\"\(bucketId)\", \"fileNamePrefix\":\"\(fileNamePrefix)\", \"validDurationInSeconds\":\(validDuration)}".data(using: .utf8)!

// Create the task
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
	if let data = data {
		let json = String(data: data, encoding: .utf8)
		print("\(json!)")
	}
}

task.resume()

// Swift 4.1 (swiftlang-902.0.48 clang-902.0.37.1) Xcode 9.3.1 (9E501)

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

require 'json'
require 'net/http'

api_url = "" # Provided by b2_authorize_account
bucket_id = "" # The bucket that files can be downloaded from
file_name_prefix = "" # The file name prefix of files the download authorization will allow
valid_duration = 86400 # The number of seconds the authorization is valid for
account_authorization_token = "" # Provided by b2_authorize_account
uri = URI.join("#{api_url}/b2api/v2/b2_get_download_authorization")
req = Net::HTTP::Post.new(uri)
req.add_field("Authorization","#{account_authorization_token}")
req.body = "{\"bucketId\":\"#{bucket_id}\", \"fileNamePrefix\":\"#{file_name_prefix}\", \"validDurationInSeconds\":#{valid_duration}}"
http = Net::HTTP.new(req.uri.host, req.uri.port)
http.use_ssl = true
res = http.start {|http| http.request(req)}
case res
when Net::HTTPSuccess then
    res.body
when Net::HTTPRedirection then
    fetch(res['location'], limit - 1)
else
    res.error!
end

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

String apiUrl = "API_URL"; // Provided by b2_authorize_account 
String accountAuthorizationToken = "ACCOUNT_AUTHORIZATION_TOKEN"; // Provided by b2_authorize_account 
String bucketId = "BUCKET_ID"; // The bucket that files can be downloaded from
String fileNamePrefix = "FILE_NAME_PREFIX"; // The file name prefix of files the download authorization will allow
int validDuration = 86400; // The number of seconds the authorization is valid for

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(apiUrl + "/b2api/v2/b2_get_file_info");
string body = "{\"bucketId\":\"" + bucketId + "\", \"fileNamePrefix\":\"" + fileNamePrefix + "\", \"validDurationInSeconds\":" + validDuration + "}";
var data = Encoding.UTF8.GetBytes(body);
webRequest.Method = "POST";
webRequest.Headers.Add("Authorization", accountAuthorizationToken);
webRequest.ContentType = "application/json; charset=utf-8";
webRequest.ContentLength = data.Length;
using (var stream = webRequest.GetRequestStream())
{
	stream.Write(data, 0, data.Length);
	stream.Close();
}
WebResponse response = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
response.Close();
Console.WriteLine(responseString);

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}

Code

$api_url = ""; // From b2_authorize_account call
$auth_token = ""; // From b2_authorize_account call
$bucket_id = ""; // The bucket that files can be downloaded from
$valid_duration = 86400; // The number of seconds the authorization is valid for
$file_name_prefix = ""; // The file name prefix of files the download authorization will allow

$session = curl_init($api_url .  "/b2api/v2/b2_get_download_authorization");

// Add post fields
$data = array("bucketId" => $bucket_id, 
              "validDurationInSeconds" => $valid_duration, 
              "fileNamePrefix" => $file_name_prefix);
$post_fields = json_encode($data);
curl_setopt($session, CURLOPT_POSTFIELDS, $post_fields); 

// Add headers
$headers = array();
$headers[] = "Authorization: " . $auth_token;
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); 

curl_setopt($session, CURLOPT_POST, true); // HTTP POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);  // Receive server response
$server_output = curl_exec($session); // Let's do this!
curl_close ($session); // Clean up
echo ($server_output); // Tell me about the rabbits, George!

Output

{
  "authorizationToken": "3_20160803004041_53982a92f631a8c7303e3266_d940c7f5ee17cd1de3758aaacf1024188bc0cd0b_000_20160804004041_0006_dnld",
  "bucketId": "a71f544e781e6891531b001a",
  "fileNamePrefix": "public"
}