JavaScript is required to use Bungie.net

HELP

2/13/2017
Developers: Bungie.net Authentication
All Platforms
This article describes a new sanctioned authentication method for third party app developers. This method has several benefits over the technique currently used by apps that are performing authentication:
  • It uses OAuth 2.0 style sign in flow, and does not depend on fragile cookies.
  • It gives the user a chance to review the scope of permissions granted to an application so they can understand what the application can do on their behalf.
  • Users can review all write operations performed by an application, and disable apps they no longer wish to have access.
  • It's sanctioned by Bungie, and we will smile upon apps that use this mechanism instead of cookies. Also, this is the only mechanism permitted by our terms of service for application developers to make use of APIs that require authentication.

This document is a guide for application developers creating applications that make use of this mechanism. This document assumes the reader is familiar with Bungie.net API’s and application development.  

Note: Bungie does not provide support for this feature or for any API related functionality. Please direct questions to the BungieNetPlatform group where other community developers can provide assistance.

History

1.0 Initial Version

Overview

Before an application can call Bungie.net APIs that require authentication, the application must acquire an Access Token. The Access Token is added to the Authorization header of each platform request. Here is an example request:

GET https://www.bungie.net/Platform/User/GetBungieNetUser/ HTTP/1.1
Host: www.bungie.net
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
Origin: https://example.com
User-Agent: app-platform
Authorization: Bearer CHMS5gEAIGouCzYA...CWpeDmBF2SN9Khan7Q==
X-API-Key: 6747e6eaab87471cb98620895e554c69

There are two important headers to note: X-API-Key and Authorization.

The X-API-Key is the usual header that identifies an application to Bungie.net. If you have been developing apps for Bungie.net, you are already familiar with the X-API-Key header.  The Access Token appears after the word ‘Bearer’ on the Authorization header.  It has been truncated for clarity in the example, but it contains everything Bungie.net needs, combined with your API key to identify the user and permit your application to perform actions on behalf of that user.

After defining your application in the Bungie.net application portal, there are a few steps needed to get an Access Token:



  1. Direct the user to Bungie.net using a special Authorization URL dedicated for your application, including a state parameter your app creates.
  2. Wait for the user to review your request, and press the Approve button
  3. Receive an Authorization Code from Bungie.net at your preconfigured Redirect URL (more about this later). Verify the received state parameter matches the one you supplied in step 1. Stop here if it does not match.
  4. Call the GetAccessTokensFromCode API on Bungie.net supplying the Authorization Code you just received.
  5. The reply to GetAccessTokenFromCode will provide both an Access Token and a Refresh Token. More about Refresh Tokens in a moment.

Step 1 requires your application to open a web browser directed at a special URL crafted just for your application. This URL is available on the Bungie.net application portal described later.

The web browser will display a page similar to the following:

 
Step 2 consists of the user pressing the “Approve” button. This button will result in Bungie.net redirecting the web browser back to your application via the Redirect URL, which is something you already configured in the Bungie.net application portal.

The response looks like this:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: https://example.com/signin?code=9229e57fe21932f05c14aa887d44f17a&state=somethingfromyourapp

The location header will contain your Redirect URL with a code parameter that contains the Authorization Code. This code is only valid for a few minutes and can only be used by trading it in for a more valuable Access Token and Refresh Token.
Step 3 is when your application is invoked again by your platform. In the case of a web browser, this will pass the code as a query string parameter at the address you specify. If you are creating a mobile app, the Redirect URL may use a scheme that uniquely identifies your application which will be launched by the platform. In any case, the Authorization Code will come in the query string parameter ‘code’.

Step 4 happens when you invoke the GetAccessTokensFromCode API on Bungie.net, passing the code as input. That request looks like this:
POST https://www.bungie.net/Platform/App/GetAccessTokensFromCode/
Host: www.bungie.net
Accept: application/json
Origin: https://example.com
User-Agent: app-platform
Content-Length: 43
X-API-Key: 6747e6eaab87471cb98620895e554c69
Content-Type: application/json; charset=UTF-8;
 
{"code":"9229e57fe21932f05c14aa887d44f17a"}
 
Response:

HTTP/1.1 200 OK
Content-Length: 900
Content-Type: application/json; charset=utf-8
 
{
     "Response": {
           "accessToken": {
                "value": "CHMS5gEAIGou...szvcBJaYrjn6OTmSN9Khan7Q==",
                "readyin": 0,
                "expires": 3600
           },
           "refreshToken": {
                "value": "CHMShgIAIG....wm/MI3AOdxRXvbREXhoL797Em",
                "readyin": 1800,
                "expires": 7776000
           },
           "scope": 129
     },
     "ErrorCode": 1,
     "ThrottleSeconds": 0,
     "ErrorStatus": "Success",
     "Message": "Ok",
     "MessageData": {          
     }
}

That’s it! The Access Token is right there, ready to be added to the Authorization header of your favorite Bungie.net API.


Details


Refresh Token

If you were paying attention, you noticed the Access Token you received is only valid for 3600 seconds. That is just an hour.  That won’t get you very far.  When the token expires, it will stop working and you need to get another one.  You could keep popping open a web browser and asking your user to approve again, and then trade the Authorization Code for a fresh Access Token.  That works, but your user will be unhappy.

Instead, you can use the Refresh Token to get a new Access Token by calling the GetAccessTokensFromRefreshToken API.  Like this:

POST https://www.bungie.net/Platform/App/GetAccessTokensFromRefreshToken/
Host: www.bungie.net
Accept: application/json
Origin: https://example.com
User-Agent: app-platform
Content-Length: 487
X-API-Key: 6747e6eaab87471cb98620895e554c69
Content-Type: application/json; charset=UTF-8;
 
{"refreshToken":"CHMShgIAIG....wm/MI3AOdxRXvbREXhoL797Em"}

Response:

HTTP/1.1 200 OK
Content-Length: 900
Content-Type: application/json; charset=utf-8
 
{
     "Response": {
           "accessToken": {
                "value": "CH4Ikj9Gou...szvcBJaYrjn63kIhdBxQ9h00==",
                "readyin": 0,
                "expires": 3600
           },
           "refreshToken": {
                "value": "CH98HY9382....sd9283cIiEJE97Sww",
                "readyin": 1800,
                "expires": 7776000
           },
           "scope": 129
     },
     "ErrorCode": 1,
     "ThrottleSeconds": 0,
     "ErrorStatus": "Success",
     "Message": "Ok",
     "MessageData": {          
     }
}
Not only do you get a fresh Access Token that is good for another hour, you get a new Refresh Token good for another 90 days.  Your user does not need to be involved in the interaction.  The permission they granted the first time continues to apply unless they have revoked it. If the user did revoke your app (for whatever reason), you will need to get their permission again using the 5 step Authorization flow described earlier.

As long as your application gets a new Refresh Token every 90 days, your application can continue to take actions on a user’s behalf for up to one year after which you will need to start over with the Authorization flow.
A few important details about Refresh Tokens:
  • The Refresh Token is not valid for 1800 seconds after you acquire it, as indicated by the readyin property.  This means you must use the Access Token for at least 30 minutes before you can get another one.  If your app shuts down or is deactivated before the 30 minutes passes,  you will want to store both the Access Token and the Refresh Token, along with their expiration times, in a safe place so you have access to both when the application restarts.
  • Treat the Access Token and Refresh Token like passwords.  Keep them in your platform’s secure storage facility.  Take great care not to let these values escape from your user’s device or from your care if you are a server based application.
  • If your application runs in a web browser, the current recommendation is to store these values in local storage.


Scope

Bungie.net offers a range of APIs an application can call, each dipping into different feature areas. For example, a user could use your application to review or modify their profile, post to forums, or groups, review their game play information, transfer items between characters, etc. Many applications will focus on features related to transferring items between characters, or examining a characters inventory. So why bother getting permission from your user to do anything else?  Your scope, set in the Bungie.net application portal, declares which APIs you care about so Bungie.net can let the user know what your applications might do.  The Access Token your application uses to prove it has permission to call an API on behalf of a user includes this scope and the platform will make sure calls to other APIs are disallowed.

The scope protects your user by letting them have some insight into what an application may do, and it limits the damage that can be done should an Access Token or Refresh Token somehow get stolen. For these reasons, you should choose only the scopes you need.

ScopeValueDescription
ReadBasicUserProfile 
1Read user profile information such as the user's handle, Xbox and PSN account names, and Destiny characters.
MoveEquipDestinyItems 
32 
Move or equip Destiny items
ReadDestinyInventoryAndVault
64 
Read user's Destiny vault and character inventory.
ReadUserData 128 
Read user data such as web notifications, clan/group memberships,   recent activity, and muted users.
ReadDestinyVendorsAndAdvisors 512 
Access vendor and advisor data specific to a user.
  
 
The ReadBasicUserProfile scope is implicitly included in the scope of all applications. It permits a call to GetCurrentBungieAccount, which is sufficient to determine that a user has control of a particular account. You may configure additional scopes in the portal.

If you change your application’s scope after a user has authorized it, the Refresh Token for that user will still only include the scope that user authorized.  To expand (or contract) your scope, you must repeat the authorization flow described at the beginning of this document, thus informing the user of the change.  The user must approve all items requested by your scope, so you will not need to worry about some APIs working while others do not.

If you do change your scope, your application can detect when it encounters a user with a different scope because the response to the GetAccessTokenFromRefreshToken call includes the scope granted by that user.  If this scope is not what you expect, you can either work with it, or repeat the authorization flow again.

The following links provide a summary of the APIs available on Bungie.net.  The ‘Scope’ column on each page indicates the scope required to call the API.  If there is not a scope mentioned, then the API does not require authentication and can be called with any scope.

https://www.bungie.net/platform/User/help/
https://www.bungie.net/platform/Notification/help/
https://www.bungie.net/platform/Activity/help/
https://www.bungie.net/platform/Destiny/help/

Redirect URL

In order to receive an Authorization Code you must have a Redirect URL configured in the Bungie.net application portal. If you are hosting your application on a web server, the Redirect URL must be secured using TLS and thus an ‘https’ scheme is required. A URL with an ‘http’ scheme is not permitted.

Your Redirect URL is the primary way Bungie.net avoids passing an Authorization Code to a malicious application.  Your application’s platform will always be redirected to the URL you provide in order to pass the Authorization Code.  An attacker has no means to modify this URL or suggest a different URL.

You do not need to provision a Redirect URL if your application does not need to call authenticated APIs. The Bungie.net application portal can still be used to get your API keys needed for unauthenticated API calls.

Origin

If your application is a Chrome extension or uses JavaScript in a web browser to call API’s on Bungie.net, you will need to configure your application’s Origin in the Bungie.net application portal. The Origin header is added by the web browser to each request sent to Bungie.net. It is a security feature that lets Bungie.net know the request may not be friendly. As long as your API key is linked to a known application, and the Origin header matches the one we have on file, the request is permitted.

You can determine your origin by examining the Request headers generated by your browser in your browser’s developer tools. Take this request from a previous example.

POST https://www.bungie.net/Platform/App/GetAccessTokensFromCode/
Host: www.bungie.net
Accept: application/json
Origin: https://example.com
User-Agent: app-platform
Content-Length: 43
X-API-Key: 6747e6eaab87471cb98620895e554c69
Content-Type: application/json; charset=UTF-8;
The Origin in this case is ‘https://example.com’ exactly as it appears in the request.

Even if your application will only call APIs that do not require authentication, you can benefit by linking your Origin to your API key. API calls that were previously not permitted due security features related to Cross Origin Resource Sharing (CORS) will start to work.

Origin requirement

Bungie.net requires that if a platform request contains an origin header that it match the origin header registered with the application as determined by the API key in that request. If there is not a match, or the origin has not been configured for the application the request will be rejected.

This is a defense in depth measure that narrows the usefulness of an API key. Since web browsers should add the origin header outside of the control of the application, an API key used in a context where it was not intended will not work. For example, if the key is accidentally copied from a source code repository, or taken from another application. There is a long list of cases where this measure has no impact, and so it is far from a thorough security feature.

Application developers that are hindered by the origin header either because the value of the header is unpredictable due to some nuance of the platform they are using, or they have a few different origin values possible may do one of the following in the Bungie.net application portal:
  • Configure the value of the origin to "*" (without the quotes)
  • Provide a comma separated list of origin values (up to 200 characters total).
The "*" option provides the most flexibility, but makes the API key easier to use in unintended contexts. Specifying a single specific origin or a short list of valid origins is preferred.

Cookies

Your application will not use HTTP cookies to authenticate, but we would still like you to honor any “Set-Cookie” headers received from Bungie.net. These cookies help Bungie.net manage caching of data related to your session, providing better overall performance. If you are creating a browser based app, this will happen automatically. However, if you are building your application using an HTTP stack, make use of the cookie container features provided by your platform.

Cross Site Request Forgery Mitigation

The Authorization URL accepts a ‘state’ parameter which will be echoed back on your Redirect URL. Your application should generate a random value that an attacker could not guess. It should then verify that value is the same when it gets the code back via the Redirect URL.
There are several good write-ups about the use of the state parameter on the internet with respect to OAuth 2.0.  For example:

We recommend you make use of the state parameter in your implementation.

Signing in via the System Web Browser

One of the key values of this authentication mechanism is that it makes it possible for users to enter their credentials into the default system web browser. Contrast this with using an in-app web view which can allow a mischievous application to collect a user's credentials without the user's knowledge.

Using a web view is strongly discouraged by Bungie. We will block it using technical means where possible. In the very least, applications that implement the sign in flow via a web view will not be featured or promoted on Bungie.net in any way. We may take other measures as well.

It is not that we do not trust app developers, but we want to set a consistent example for users. Users should be wary of entering credentials in applications that are not the custodians of those credentials. Users can only confirm they are authenticating with Sony, Microsoft, or Bungie if they have the user interface provided by the browser, including the URL and the https certificate information.

iOS applications may use the SFSafariViewContoller class instead of switching to Safari. Android applications may use Chrome Custom Tabs.  Web applications may not use an iframe, the URL bar where the user is authorizing or signing in must always be visible. 


Bungie.net Application Portal

The Bungie.net application portal lets you define up to 10 applications that you can name and configure. Use this portal to change your application’s name, scope, Redirect URL, Origin, and provide a link to another website that can provide more detail about your application.

You can find the portal here: https://www.bungie.net/en/Application

API Key Management

An application only needs one API key. One will be assigned to your application upon creation.

However, there are circumstances where you might like to disable an API key. For example, if you have released an application that turns out to have a bug that is causing issues, and you want to prevent it from accessing Bungie.net until you can fix it. Just disable the API key the application is using. You can create a new API key to embed in the fixed version of the application. Similarly if you discover your API key has been co-opted by another application you can disable it and replace it with a new key.  Your application may have two active API keys available at the same time so that you can roll out an updated build with the new key while the old application continues to function.  Once enough users have your new application, you can disable or even delete the old key.


Authorization URL

An Authorization URL is created for each API key assigned to applications that supply a Redirect URL. Use this URL in step 1 of the Authorization flow.  The Authorization Code generated is linked to API key associated with the particular Authorization URL, therefore it is necessary to use that same API key in the X-API-Key header when calling the GetAccessTokensFromCode.

Application State

An application may be in one of four states: Private, Public, or Disabled, or Blocked.  Applications that are either public or private are in a functioning state and can be used with any active API keys that are associated with it.  The only difference between public and private applications is discoverability.  Public applications are available through search APIs and may be featured or promoted elsewhere on Bungie.net.  Keep the application set to Private while it is in development or beta. You might even have two versions of the same application where you keep the yet to be released version in Private state. A disabled application will no longer function on Bungie.net.

Blocked is reserved for applications that have misbehaved in some way and need to be taken out of circulation. Only Bungie can change an application to the Blocked state.  Once blocked, an application will no longer work with Bungie.net and the application may not be edited by its originator.  Only Bungie may unblock an application. This will be used in exceedingly rare cases and should not be a concern to any well-meaning application developers.

Activity Logs

Every write operation your application performs is kept in an activity log that may be inspected by the affected user. This helps the user understand what your application is doing even if it was done without direct user interaction. The activity log is accessible from the user’s profile settings under Accounts & Linking.  A user may also revoke access previously granted to your application from this page.  This revocation will take place the next time your application attempts to get a new Access Token from a Refresh Token. This can be reversed by taking the user back through the Authorization flow.

Conclusion

A robust authorization mechanism that allows users to review their applications activity and control access to their Bungie.net account is fundamental to building an application ecosystem that can expand the way our community interacts with Destiny and Bungie.net. This document hopefully provided what you need to get started.  Be sure to check out the BungieNetPlatform group (https://www.bungie.net/en/Clan/Forum/39966) where you can ask questions and get help from Bungie developers and other community members.

preload icon
preload icon
preload icon
You are not allowed to view this content.