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.

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 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

message

400

bad_request

Wrong host name for request

401

missing_auth_token

Authorization token is missing

401

expired_auth_token

Authorization token has expired

401

bad_auth_token

Invalid authorization token

401

bad_auth_token

Authorization token for wrong cluster

400

bad_request

bad bucketId

400

bad_request

fileNamePrefix must be specified

400

bad_request

validDurationInSeconds must be >= 0

400

bad_request

validDurationInSeconds cannot be greater than a week

503

service_unavailable

<various>

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/v1/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 file name prefix of files the download authorization will allow
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/v1/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 file name prefix of files the download authorization will allow
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/v1/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 file name prefix of files the download authorization will allow
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
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL:NSURL(string: "\(apiUrl)")!.URLByAppendingPathComponent("/b2api/v1/b2_get_download_authorization"))
request.HTTPMethod = "POST"
request.addValue(accountAuthorizationToken, forHTTPHeaderField: "Authorization")
request.HTTPBody = "{\"bucketId\":\"\(bucketId)\", \"fileNamePrefix\":\"\(fileNamePrefix)\", \"validDurationInSeconds\":\"\(validDuration)\"}".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let task = session.dataTaskWithRequest(request, completionHandler:{ (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
    if data != nil {
        let json = NSString(data: data, encoding:NSUTF8StringEncoding)
    }
})
task.resume()

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 file name prefix of files the download authorization will allow
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/v1/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 file name prefix of files the download authorization will allow
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/v1/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 file name prefix of files the download authorization will allow
$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/v1/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"
}