> ## Documentation Index
> Fetch the complete documentation index at: https://developer.box.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OAuth 2.0 with SDKs

export const MultiRelatedLinks = ({sections = []}) => {
  if (!sections || sections.length === 0) {
    return null;
  }
  return <div className="space-y-8">
      {sections.map((section, index) => <RelatedLinks key={index} title={section.title} items={section.items} />)}
    </div>;
};

export const RelatedLinks = ({title, items = []}) => {
  const getBadgeClass = badge => {
    if (!badge) return "badge-default";
    const badgeType = badge.toLowerCase().replace(/\s+/g, "-");
    return `badge-${badge === "ガイド" ? "guide" : badgeType}`;
  };
  if (!items || items.length === 0) {
    return null;
  }
  return <div className="my-8">
      {}
      <h3 className="text-sm font-bold uppercase tracking-wider mb-4">{title}</h3>

      {}
      <div className="flex flex-col gap-3">
        {items.map((item, index) => <a key={index} href={item.href} className="py-2 px-3 rounded related_link hover:bg-[#f2f2f2] dark:hover:bg-[#111827] flex items-center gap-3 group no-underline hover:no-underline border-b-0">
            {}
            <span className={`px-2 py-1 rounded-full text-xs font-semibold uppercase tracking-wide flex-shrink-0 ${getBadgeClass(item.badge)}`}>
              {item.badge}
            </span>

            {}
            <span className="text-base">{item.label}</span>
          </a>)}
      </div>
    </div>;
};

export const Link = ({href, children, className, ...props}) => {
  const localizedHref = localizeLink(href);
  return <a href={localizedHref} className={className} {...props}>
      {children}
    </a>;
};

<RelatedLinks
  title="REQUIRED GUIDES"
  items={[
{ label: translate("Box SDKs"), href: "/guides/tooling/sdks/index", badge: "GUIDE" },
{ label: translate("Select Auth Method"), href: "/guides/authentication/select", badge: "GUIDE" },
{ label: translate("Setup with OAuth 2.0"), href: "/guides/authentication/oauth2/oauth2-setup", badge: "GUIDE" }
]}
/>

The Box SDKs have built-in support for client-side OAuth 2.0.

In the process a user is redirected to the Box web app in a browser where they
log in and authorize the application access to their data before they are
redirected back to the applications `redirect_url`. This last step requires the
application to be running on a web server somewhere accessible to the user.

## Overview

To complete an OAuth 2.0 flow the following steps need to be completed.

1. Configure the Box SDK
2. Redirect the user to the Box website
3. The user grants the application access
4. Exchange the authorization code for an access token

At the end of this flow, the application has an Access Token that can be used to
make API calls on behalf of this user.

<Note>
  The access token acquired through OAuth 2.0 is inherently tied to the user who
  authorized the application. Any API call made with this token will seem to
  come from this application, and the user needs to have access to any file or
  folder the application tries to access with this token.
</Note>

## Parameters

| Parameter       | Description                                                                                                                                                   |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CLIENT_ID`     | The client ID or API key for the application                                                                                                                  |
| `CLIENT_SECRET` | The client secret or API secret for the application                                                                                                           |
| `REDIRECT_URI`  | The redirect URL for your application that a user will be sent to after they have authorized the application. This can be configured in the developer console |

## 1. Configure SDK

The first step is to make sure your environment has been prepared with the SDK of
your choice.

<CodeGroup>
  ```csharp .NET theme={null}
  var redirectUrl = "[REDIRECT_URI]";
  var config = new BoxConfig("[CLIENT_ID]", "[CLIENT_SECRET]", new Uri(redirectUrl));
  var sdk = new BoxClient(config);
  ```

  ```java Java theme={null}
  import com.box.sdk.BoxAPIConnection;

  String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code";
  ```

  ```python Python theme={null}
  from boxsdk import OAuth2, Client

  auth = OAuth2(
      client_id='[CLIENT_ID]',
      client_secret='[CLIENT_SECRET]'
  )
  ```

  ```js Node theme={null}
  var BoxSDK = require("box-node-sdk");

  var sdk = new BoxSDK({
      clientID: "[CLIENT_ID]",
      clientSecret: "[CLIENT_SECRET]",
  });
  ```
</CodeGroup>

<Card href={localizeLink("/guides/tooling/sdks")} arrow title="Learn more about installing an SDK for your environment" />

## 2. Redirect user

Next, redirect the user to the authorization URL. Most of the SDKs support a
way to get the authorization URL for an SDK client.

<Warning>
  If you configured multiple redirect URIs for the application, the authorization
  URL must include the `redirect_uri` parameter matching one of the URIs
  configured in the developer console. If the parameter is not specified, the
  user will see a `redirect_uri_missing` error and will not be redirected back to
  the app after granting application access.
</Warning>

<CodeGroup>
  ```csharp .NET theme={null}
  var authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code";
  // redirectTo(authorizationUrl);
  ```

  ```java Java theme={null}
  String authorizationUrl = "https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&response_type=code";

  // response.redirect(authorizationUrl);
  ```

  ```python Python theme={null}
  auth_url, csrf_token = auth.get_authorization_url('[REDIRECT_URL]')

  // redirect(auth_url, code=302)
  ```

  ```js Node theme={null}
  var authorize_url = sdk.getAuthorizeURL({
      response_type: "code",
  });

  // res.redirect(authorize_url)
  ```
</CodeGroup>

<Info>
  The way in which a user is redirected to a URL depends on the application
  framework used. Most framework documentation provides extensive guidance on
  this topic.
</Info>

The <Link href="/reference/get-authorize">authorization URL</Link> can also be created manually
as follows.

```sh theme={null}
https://account.box.com/api/oauth2/authorize?client_id=[CLIENT_ID]&redirect_uri=[REDIRECT_URI]&response_type=code
```

<Info>
  Additional query parameters can be passed along when redirecting the user to
  limit down the scope, or pass along some extra state. See the [reference
  documentation](/reference/get-authorize) for more information.
</Info>

## 3. User grants application access

Once the user is redirected to the Box web app they will have to log in. After
they logged in they are presented with a screen to approve your application.

<Frame border center shadow width="400">
  <img src="https://mintcdn.com/box/J_EwM_J-GUl8Mc67/guides/authentication/oauth2/oauth2-grant.png?fit=max&auto=format&n=J_EwM_J-GUl8Mc67&q=85&s=4ca6c68db41c0276cf20d44b2a9ee76f" alt="Example OAuth 2.0 approval screen" width="796" height="890" data-path="guides/authentication/oauth2/oauth2-grant.png" />
</Frame>

When the user accepts this requests and clicks the button, the browser will
redirect to your application's redirect URL as configured in the developer console.

## 4. Exchange code

The user is redirected to your application's redirect URL with a query parameter
containing a short-lived authorization code.

```sh theme={null}
https://your.domain.com/path?code=1234567
```

This code is not an <Link href="/guides/authentication/tokens/access-tokens">Access Token</Link> and is only valid for a few seconds.
The SDKs can be used to exchange the code for an actual Access Token.

<CodeGroup>
  ```csharp .NET theme={null}
  var session = await sdk.Auth.AuthenticateAsync("[CODE]");
  var client = new BoxClient(config, session);
  ```

  ```java Java theme={null}
  BoxAPIConnection client = new BoxAPIConnection(
      "[CLIENT_ID]",
      "[CLIENT_SECRET]",
      "[CODE]"
  );
  ```

  ```python Python theme={null}
  auth.authenticate('[CODE]')
  client = Client(auth)
  ```

  ```js Node theme={null}
  var code = "...";

  sdk.getTokensAuthorizationCodeGrant("[CODE]", null, function (err, tokenInfo) {
      var client = sdk.getPersistentClient(tokenInfo);
  });
  ```
</CodeGroup>

At the end of this flow, the application has an Access Token that can be used to
make API calls on behalf of this user.

## Using SDKs and OAuth 2.0

To learn more about OAuth 2.0 authentication for each SDK head over to:

* [.Net][.Net]
* [Java][Java]
* [Python][Python]
* [Node][Node]
* [IOS][IOS]

[.Net]: https://github.com/box/box-windows-sdk-v2/blob/legacy/docs/authentication.md#traditional-3-legged-oauth2

[Java]: https://github.com/box/box-java-sdk/blob/legacy/doc/authentication.md#standard-3-legged-oauth-20

[Python]: https://github.com/box/box-python-sdk/blob/legacy/docs/usage/authentication.md#traditional-3-legged-oauth2

[Node]: https://github.com/box/box-node-sdk/blob/legacy/docs/authentication.md#traditional-3-legged-oauth2

[IOS]: https://github.com/box/box-ios-sdk/blob/legacy/BoxSDK/docs/usage/authentication.md#traditional-3-legged-oauth2

[1]: https://support.box.com/hc/en-us/articles/360043693554-Box-Verified-Enterprise-Supported-Apps

<RelatedLinks
  title="RELATED APIS"
  items={[
{ label: translate("Authorize user"), href: "/reference/get-authorize", badge: "GET" }
]}
/>

<RelatedLinks
  title="RELATED GUIDES"
  items={[
{ label: translate("Platform App"), href: "/guides/applications/platform-apps/index", badge: "GUIDE" },
{ label: translate("Select Auth Method"), href: "/guides/authentication/select", badge: "GUIDE" },
{ label: translate("Setup with OAuth 2.0"), href: "/guides/authentication/oauth2/oauth2-setup", badge: "GUIDE" }
]}
/>
