# Security callbacks

Instead of providing credentials once during SDK instantiation, pass a custom authentication function that allows end users to manage secrets dynamically. Custom authentication functions can be used to automatically refresh tokens or retrieve secrets from a secret store.

## Language support

## Example: Bearer authentication

In this example, bearer authentication is used as the only security scheme:

```yaml
security:
  - bearerAuth: []
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
```

The callback function passed when initializing the SDK acts as a _security source_ and is called whenever a request is made, allowing tokens to be refreshed if needed.

<CodeWithTabs client:visible
  tabs={[
    {
      label: "TypeScript",
      language: "typescript",
      code: `import { SDK } from "<packageName>";

  const sdk = new SDK({
    security: async (): Promise<Security> => {
      // refresh token here
      const token = "<YOUR_JWT>";
      return { bearerAuth: token };
    },
  });`,
    },
    {
      label: "Python",
      language: "python",
      code: `import requests

  class BearerSource implements SecuritySource {

      public Security getSecurity() {
          // refresh token here
          return Security.builder()
              .bearerAuth("<YOUR_JWT>")
              .build();
      }
  }

  _____________________________________

  SDK s = SDK.builder()
      .securitySource(new BearerSource())
      .build();`,
    },
    {
      label: "C#",
      language: "csharp",
      code: `using Speakeasy;
  using Speakeasy.Models.Components;

  Func<Security> tokenSource = () =>
  {
      // refresh token here
      var token = "<YOUR_JWT>"

      return new Security { BearerAuth = token}
  }

  var sdk = new SDK(securitySource: tokenSource);`,
    },
    {
      label: "PHP",
      language: "php",
      code: `use Speakeasy\\Speakeasy;

  $sdk = Speakeasy\\SDK::builder()
      ->setSecuritySource(
          function (): Security {
              //refresh token here
              var token = "<YOUR_JWT>";

              return new Security(bearerAuth: $token);
          }
      )->build();

  try {
      $res = $sdk->drinks->listDrinks();

      if ($res->Drinks != null) {
          // handle response
      }
  } catch (Errors\\ErrorThrowable $e) {
      // handle exception
  }`,
    },
    {
      label: "Ruby",
      language: "ruby",
      code: `require 'speakeasy'

  sdk = Speakeasy::SDK.new(
    security_source: -> {
      # Refresh token here
      token = '<YOUR_JWT>'

      Models::Components::Security.new(bearer_auth: token)
    }
  )

  res = sdk.drinks.list_drinks`,
}
]}
/>
