Autorize o acesso interativo a Databricks recurso com um usuário account usando OAuth
Este tópico fornece etapas e detalhes para autorizar o acesso a Databricks recurso ao executar interativamente Databricks CLI comando ou chamar Databricks REST APIs.
Databricks usa o OAuth como o protocolo preferencial para autorização e autenticação de usuários ao interagir com o Databricks recurso fora da interface do usuário. Databricks também fornece a ferramenta de autenticação de cliente unificada para automatizar o refresh do acesso tokens gerado como parte do método de autenticação do OAuth.
Para obter mais detalhes de alto nível, consulte Autorização de acesso a Databricks recurso.
Quais são as minhas opções de autorização e autenticação ao acessar Databricks recurso?
Neste tópico, a autorização se refere ao protocolo (OAuth) usado para negociar o acesso a um recurso específico do Databricks por meio de delegação. A autenticação refere-se ao mecanismo pelo qual as credenciais são representadas, transmitidas e verificadas - que, nesse caso, são tokens de acesso .
Databricks usa a autorização baseada emOAuth 2.0para permitir o acesso a Databricks account e workspace recurso da linha de comando ou código em nome de um usuário com as permissões para acessar esses recursos. Depois que um usuário inicialmente faz login e consente com a solicitação de autenticação OAuth, um token OAuth é fornecido à ferramenta participante ou SDK para executar a autenticação baseada em tokens em nome do usuário a partir desse momento. Os tokens de acesso OAuth têm uma vida útil de uma hora, após a qual a ferramenta ou o site SDK envolvido fará uma tentativa automática em segundo plano para obter um novo token que também é válido por uma hora.
Databricks Há duas maneiras de autorizar o acesso de um usuário account com OAuth:
- Principalmente de forma automática, usando o suporte de autenticação de cliente unificado do Databricks. Use essa abordagem simplificada se estiver usando SDKs específicos da Databricks (como o SDK do Databricks Terraform) e ferramentas. As ferramentas e os SDKs compatíveis estão listados em Autenticação de cliente unificada da Databricks.
- Manualmente, gerando diretamente um par verificador/desafio de código OAuth e um código de autorização, e usando-os para criar os tokens OAuth iniciais que o senhor fornecerá na sua configuração. Use essa abordagem quando não estiver usando uma API compatível com a autenticação de cliente unificada da Databricks. Para obter mais detalhes, consulte: Gerar e usar manualmente tokens de acesso para autenticação OAuth de usuário para máquina (U2M).
Autorização interativa de usuários com a autenticação unificada de clientes da Databricks
Antes de começar a configurar sua autorização, revise as permissões do ACL para a categoria específica de operações que você realizará nos objetos do workspace e determine se o seu account tem o nível de acesso necessário. Para obter mais detalhes, consulte Listas de controle de acesso.
Para executar a autorização OAuth com SDKs e ferramentas da Databricks que oferecem suporte à autenticação unificada do cliente, integre o seguinte em seu código:
- Environment
- Profile
- CLI
- Connect
- VS Code
- Terraform
- Python
- Java
- Go
To use environment variables for a specific Databricks authentication type with a tool or SDK, see Authorizing access to Databricks resources or the tool’s or SDK’s documentation. See also Environment variables and fields for client unified authentication and the Default methods for client unified authentication.
For account-level operations, set the following environment variables:
DATABRICKS_HOST
, set to the value of your Databricks account console URL,https://accounts.cloud.databricks.com
.DATABRICKS_ACCOUNT_ID
For workspace-level operations, set the following environment variables:
DATABRICKS_HOST
, set to the value of your Databricks workspace URL, for examplehttps://dbc-a1b2345c-d6e7.cloud.databricks.com
.
Create or identify a Databricks configuration profile with the following fields in your .databrickscfg
file. If you create the profile, replace the placeholders with the appropriate values. To use the profile with a tool or SDK, see Authorizing access to Databricks resources or the tool’s or SDK’s documentation. See also Environment variables and fields for client unified authentication and the Default methods for client unified authentication.
For account-level operations, set the following values in your .databrickscfg
file. In this case, the Databricks account console URL is https://accounts.cloud.databricks.com
:
[<some-unique-configuration-profile-name>]
host = <account-console-url>
account_id = <account-id>
For workspace-level operations, set the following values in your .databrickscfg
file. In this case, the host is the Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
:
[<some-unique-configuration-profile-name>]
host = <workspace-url>
For the Databricks CLI, run the databricks auth login
command with the following options:
- For Databricks account-level operations,
--host <account-console-url> --account-id <account-id>
. - For Databricks workspace-level operations,
--host <workspace-url>
.
After you run this command, follow the instructions in your web browser to log in to your Databricks account or workspace.
For more details, see OAuth authorization with the Databricks CLI.
OAuth U2M authentication is supported in the following Databricks Connect versions:
-
For Python, Databricks Connect for Databricks Runtime 13.1 and above.
-
For Scala, Databricks Connect for Databricks Runtime 13.3 LTS and above.
For Databricks Connect, you can do one of the following:
- Set the values in your
.databrickscfg
file for Databricks workspace-level operations as specified in this article’s “Profile” section. Also set thecluster_id
environment variable in your profile to your workspace instance URL, for examplehttps://dbc-a1b2345c-d6e7.cloud.databricks.com
. - Set the environment variables for Databricks workspace-level operations as specified in this article’s “Environment” section. Also set the
DATABRICKS_CLUSTER_ID
environment variable to your workspace instance URL, for examplehttps://dbc-a1b2345c-d6e7.cloud.databricks.com
.
Values in your .databrickscfg
file always take precedence over environment variables.
To initialize the Databricks Connect client with these environment variables or values in your .databrickscfg
file, see Compute configuration for Databricks Connect.
For the Databricks extension for Visual Studio Code, do the following:
- In the Configuration pane, click Configure Databricks.
- In the Command Palette, for Databricks Host, enter your workspace URL, for example
https://dbc-a1b2345c-d6e7.cloud.databricks.com
, and then pressEnter
. - Select OAuth (user to machine).
- Complete the on-screen instructions within your web browser to finish authenticating with your Databricks account and allowing all-apis access.
For more details, see OAuth U2M authorization with the Databricks CLI.
For both account-level and workspace-level operations, you must use the Databricks CLI to run the following command before you apply your Terraform configuration. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
within your user’s home folder on your machine:
Configuring for Databricks account-level operations
databricks auth login --host <account-console-url> --account-id <account-id>
Replace the following placeholders:
-
Replace
<account-console-url>
with the valuehttps://accounts.cloud.databricks.com
. (Do not set this to the value of your Databricks workspace URL.) -
Replace
<account-id>
with the value of your Databricks account. See Locate your account ID.
If you have an existing Databricks configuration profile with the host
and account_id
fields already set, you can substitute --host <account-console-url> --account-id <account-id>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the account login URL and account ID as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Terraform code similar to one of the following snippets:
provider "databricks" {
alias = "account"
}
For direct configuration, set the provider
using the following configuration. Replace the retrieve-
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as HashiCorp Vault. See also Vault Provider). In this example, you can set account_id
to your Databricks account console URL.
provider "databricks" {
alias = "account"
host = <retrieve-account-console-url>
account_id = <retrieve-account-id>
}
Configuring for Databricks workspace-level operations
databricks auth login --host <workspace-url>
Replace the placeholder <workspace-url>
with the target Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
.
If you have an existing Databricks configuration profile with the host
field already set, you can substitute --host <workspace-url>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the workspace URL as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Terraform code similar to one of the following snippets:
provider "databricks" {
alias = "workspace"
}
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as HashiCorp Vault. See also Vault Provider). In this case, the host is the Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
:
provider "databricks" {
alias = "workspace"
host = <retrieve-workspace-url>
}
For more information about authenticating with the Databricks Terraform provider, see Authentication.
For both account-level and workspace-level operations, you must use the Databricks CLI to run the following command before you run your Python code. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
within your user’s home folder on your machine:
Configuring for Databricks account-level operations
databricks auth login --host <account-console-url> --account-id <account-id>
Replace the following placeholders:
-
Replace
<account-console-url>
with the valuehttps://accounts.cloud.databricks.com
. (Do not set this to the value of your Databricks workspace URL.) -
Replace
<account-id>
with the value of your Databricks account. See Locate your account ID.
If you have an existing Databricks configuration profile with the host
and account_id
fields already set, you can substitute --host <account-console-url> --account-id <account-id>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the account login URL and account ID as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Python code similar to one of the following snippets:
For default authorization using Databricks unified client authentication:
from databricks.sdk import AccountClient
a = AccountClient()
# ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the Databricks account console URL is https://accounts.cloud.databricks.com
:
from databricks.sdk import AccountClient
a = AccountClient(
host = retrieveAccountConsoleUrl(),
account_id = retrieveAccountId()
)
# ...
Configuring for Databricks workspace-level operations
databricks auth login --host <worskpace-url>
Replace the placeholder <workspace-url>
with the target Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
.
If you have an existing Databricks configuration profile with the host
field already set, you can substitute --host <workspace-url>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the workspace URL as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Python code similar to one of the following snippets:
For default authorization using Databricks unified client authentication:
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
# ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the host is the Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
:
from databricks.sdk import WorkspaceClient
w = WorkspaceClient(host = retrieveWorkspaceUrl())
# ...
For more information about authenticating with Databricks tools and SDKs that use Python and that implement Databricks client unified authentication, see:
For both account-level and workspace-level operations, you must use the Databricks CLI to run the following command before you run your Java code. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
in your user’s home folder on your machine:
Configuring for Databricks account-level operations
databricks auth login --host <account-console-url> --account-id <account-id>
Replace the following placeholders:
-
Replace
<account-console-url>
with the valuehttps://accounts.cloud.databricks.com
. (Do not set this to the value of your Databricks workspace URL.) -
Replace
<account-id>
with the value of your Databricks account. See Locate your account ID.
If you have an existing Databricks configuration profile with the host
and account_id
fields already set, you can substitute --host <account-console-url> --account-id <account-id>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the account login URL and account ID as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Java code similar to one of the following snippets:
For default authorization using Databricks unified client authentication:
import com.databricks.sdk.AccountClient;
// ...
AccountClient a = new AccountClient();
// ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the Databricks account console URL is https://accounts.cloud.databricks.com
:
import com.databricks.sdk.AccountClient;
import com.databricks.sdk.core.DatabricksConfig;
// ...
DatabricksConfig cfg = new DatabricksConfig()
.setHost(retrieveAccountConsoleUrl())
.setAccountId(retrieveAccountId());
AccountClient a = new AccountClient(cfg);
// ...
Configuring for Databricks workspace-level operations
For workspace-level operations, you should first use the Databricks CLI to run the following command before you run your Java code. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
within your user’s home folder on your machine:
databricks auth login --host <worskpace-url>
Replace the placeholder <workspace-url>
with the target Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
.
If you have an existing Databricks configuration profile with the host
field already set, you can substitute --host <workspace-url>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the workspace URL as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Java code similar to one of the following snippets:
For default authorization using Databricks unified client authentication:
import com.databricks.sdk.WorkspaceClient;
// ...
WorkspaceClient w = new WorkspaceClient();
// ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the host is the Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
:
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.core.DatabricksConfig;
// ...
DatabricksConfig cfg = new DatabricksConfig()
.setHost(retrieveWorkspaceUrl())
WorkspaceClient w = new WorkspaceClient(cfg);
// ...
For more information about authorizing and authenticating with Databricks tools and SDKs that use Java and that implement Databricks client unified authentication, see:
- Set up the Databricks Connect client for Scala (the Databricks Connect client for Scala uses the included Databricks SDK for Java for authentication)
- Authenticate the Databricks SDK for Java with your Databricks account or workspace
For both account-level and workspace-level operations, you must use the Databricks CLI to run the following command before you run your Go code. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
within your user’s home folder on your machine:
Configuring for Databricks account-level operations
databricks auth login --host <account-login-url> --account-id <account-id>
Replace the following placeholders:
-
Replace
<account-console-url>
with the valuehttps://accounts.cloud.databricks.com
. (Do not set this to the value of your Databricks workspace URL.) -
Replace
<account-id>
with the value of your Databricks account. See Locate your account ID.
If you have an existing Databricks configuration profile with the host
and account_id
fields already set, you can substitute --host <account-console-url> --account-id <account-id>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the account login URL and account ID as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Go code similar to one of the following snippets:
For default authorization using Databricks unified client authentication:
import (
"github.com/databricks/databricks-sdk-go"
)
// ...
a := databricks.Must(databricks.NewAccountClient())
// ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the Databricks account console URL is https://accounts.cloud.databricks.com
:
import (
"github.com/databricks/databricks-sdk-go"
)
// ...
a := databricks.Must(databricks.NewAccountClient(&databricks.Config{
Host: retrieveAccountConsoleUrl(),
AccountId: retrieveAccountId(),
}))
// ...
Configuring for Databricks workspace-level operations
For workspace-level operations, you should first use the Databricks CLI to run the following command, before you run your Go code. This command instructs the Databricks CLI to generate and cache the necessary OAuth token in the path .databricks/token-cache.json
within your user’s home folder on your machine:
databricks auth login --host <worskpace-url>
Replace the placeholder <workspace-url>
with the target Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
.
If you have an existing Databricks configuration profile with the host
field already set, you can substitute --host <workspace-url>
with --profile <profile-name>
.
After you run the auth login
command, you are prompted to save the workspace URL as a Databricks configuration profile. When prompted, enter the name of a new or existing profile in your .databrickscfg
file. Any existing profile with the same name in your .databrickscfg
file is overwritten.
If prompted, complete your web browser’s on-screen instructions to complete the login. Then use Go code similar to one of the following snippets:
import (
"github.com/databricks/databricks-sdk-go"
)
// ...
w := databricks.Must(databricks.NewWorkspaceClient())
// ...
For direct configuration (replace the retrieve
placeholders with your own implementation to retrieve the values from the console or some other configuration store, such as AWS Systems Manager Parameter Store). In this case, the host is the Databricks workspace URL, for example https://dbc-a1b2345c-d6e7.cloud.databricks.com
:
import (
"github.com/databricks/databricks-sdk-go"
)
// ...
w := databricks.Must(databricks.NewWorkspaceClient(&databricks.Config{
Host: retrieveWorkspaceUrl(),
}))
// ...
For more information about authenticating with Databricks tools and SDKs that use Go and that implement Databricks client unified authentication, see Authenticate the Databricks SDK for Go with your Databricks account or workspace.
Gerar e usar manualmente tokens de acesso para autenticação OAuth de usuário para máquina (U2M)
Esta seção é fornecida para usuários com ferramentas ou serviços de terceiros que não funcionam com o padrão de autenticação unificada do clienteDatabricks.
Se, por algum motivo, for necessário gerar manualmente, refresh, ou usar Databricks OAuth acessar tokens para OAuth autenticação U2M, siga as instruções desta seção.
Etapa 1: Gerar um verificador de código OAuth e um par de desafio de código
Para gerar e usar manualmente tokens de acesso para autenticação OAuth U2M, o senhor deve primeiro ter um verificador de código OAuth e um desafio de código OAuth derivado do verificador de código. O senhor usa o desafio de código na Etapa 2 para gerar um código de autorização OAuth. O senhor usa o verificador de código e o código de autorização na Etapa 3 para gerar os tokens de acesso OAuth.
Embora seja tecnicamente possível usar texto simples não codificado strings para o verificador de código e o desafio de código, o site Databricks recomenda enfaticamente que o senhor siga o padrão OAuth para gerar o verificador de código e o desafio de código.
Especificamente, o verificador de código deve ser uma cadeia de caracteres criptograficamente aleatória usando caracteres dos conjuntos A-Z
, a-z
, 0-9
, e os caracteres de pontuação -._~
(hífen, ponto, sublinhado e til), entre 43 e 128 caracteres. O desafio de código deve ser uma cadeia de caracteres codificada em Base64-URL do hash SHA256 do verificador de código. Para obter mais informações, consulte Solicitação de autorização.
O senhor pode executar o seguinte script Python para gerar rapidamente um verificador de código exclusivo e um par de desafios de código. Embora o senhor possa reutilizar esse verificador de código gerado e o par de desafio de código várias vezes, a Databricks recomenda que o senhor gere um novo verificador de código e um par de desafio de código toda vez que gerar manualmente tokens de acesso para autenticação OAuth U2M.
import uuid, hashlib, base64
# Generate a UUID.
uuid1 = uuid.uuid4()
# Convert the UUID to a string.
uuid_str1 = str(uuid1).upper()
# Create the code verifier.
code_verifier = uuid_str1 + "-" + uuid_str1
# Create the code challenge based on the code verifier.
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode('utf-8')
# Remove all padding from the code challenge.
code_challenge = code_challenge.replace('=', '')
# Print the code verifier and the code challenge.
# Use these in your calls to manually generate
# access tokens for OAuth U2M authentication.
print(f"code_verifier: {code_verifier}")
print(f"code_challenge: {code_challenge}")
Etapa 2: gerar um código de autorização
O senhor usa um código de autorização OAuth para gerar um token de acesso Databricks OAuth . O código de autorização expira imediatamente após o senhor usá-lo para gerar um token de acesso Databricks OAuth . O escopo do código de autorização depende do nível a partir do qual você o gera. O senhor pode gerar um código de autorização no nível Databricks account ou no nível workspace, como segue:
- Para chamar account-level e workspace-level REST APIs dentro da conta e do espaço de trabalho aos quais o usuário Databricks account tem acesso, gere um código de autorização no nível account.
- Para chamar REST APIs em apenas um workspace ao qual o usuário account tem acesso, o senhor pode gerar um código de autorização no nível workspace apenas para esse workspace.
Gerar um código de autorização de nível account
-
Como administrador da conta, faça login no console da conta.
-
Clique na seta para baixo ao lado de seu nome de usuário no canto superior direito.
-
Copie a ID de sua conta .
-
Na barra de endereço do seu navegador, navegue até o seguinte URL. Quebras de linha foram adicionadas para facilitar a leitura. Seu URL não deve conter essas quebras de linha.
No URL a seguir, substitua o seguinte:
- Substitua
<account-id>
pela ID da conta que o senhor copiou. - Substitua
<redirect-url>
por um URL de redirecionamento para sua máquina local, por exemplohttp://localhost:8020
. - Substitua
<state>
por algumas cadeias de texto simples que o senhor pode usar para verificar a integridade do código de autorização. - Substitua
<code-challenge>
pelo desafio de código que você gerou na Etapa 1.
https://accounts.cloud.databricks.com/oidc/accounts/<account-id>/v1/authorize
?client_id=databricks-cli
&redirect_uri=<redirect-url>
&response_type=code
&state=<state>
&code_challenge=<code-challenge>
&code_challenge_method=S256
&scope=all-apis+offline_access - Substitua
-
Quando solicitado, siga as instruções na tela para acessar o site log in e o seu Databricks account.
-
Na barra de endereço do seu navegador, copie o código de autorização. O código de autorização é a sequência completa de caracteres entre
code=
e o caractere&
no URL. Por exemplo, o código de autorização no URL a seguir édcod...7fe6
:http://localhost:8020/?code=dcod...7fe6&state=<state>
Você deve verificar a integridade desse código de autorização confirmando visualmente que o valor
<state>
nesse URL de resposta corresponde ao valorstate
que você forneceu no URL de solicitação. Se os valores forem diferentes, você não deve usar esse código de autorização, pois ele pode estar comprometido. -
Avance para Gerar um account-level access tokens.
Gerar um código de autorização de nível workspace
-
Na barra de endereço do seu navegador, navegue até o seguinte URL. Quebras de linha foram adicionadas para facilitar a leitura. Seu URL não deve conter essas quebras de linha.
No URL a seguir, substitua o seguinte:
- Substitua
<databricks-instance>
pelo Databricks workspace nome da instância, pordbc-a1b2345c-d6e7.cloud.databricks.com
exemplo,. - Substitua
<redirect-url>
por um URL de redirecionamento para sua máquina local, por exemplohttp://localhost:8020
. - Substitua
<state>
por algumas cadeias de texto simples que o senhor pode usar para verificar a integridade do código de autorização. - Substitua
<code-challenge>
pelo desafio de código que você gerou na Etapa 1.
https://<databricks-instance>/oidc/v1/authorize
?client_id=databricks-cli
&redirect_uri=<redirect-url>
&response_type=code
&state=<state>
&code_challenge=<code-challenge>
&code_challenge_method=S256
&scope=all-apis+offline_access - Substitua
-
Quando solicitado, siga as instruções na tela para acessar o site log in e o seu Databricks workspace.
-
Na barra de endereço do seu navegador, copie o código de autorização. O código de autorização é a sequência completa de caracteres entre
code=
e o caractere&
no URL. Por exemplo, o código de autorização no URL a seguir édcod...7fe6
:http://localhost:8020/?code=dcod...7fe6&state=<state>
Você deve verificar a integridade desse código de autorização confirmando visualmente que o valor
<state>
nesse URL de resposta corresponde ao valorstate
que você forneceu no URL de solicitação. Se os valores forem diferentes, você não deve usar esse código de autorização, pois ele pode estar comprometido.
Etapa 3: Use o código de autorização para gerar tokens de acesso OAuth
O senhor usa o código de autorização OAuth da etapa anterior para gerar um token de acesso Databricks OAuth , como segue:
- Para chamar account-level e workspace-level REST APIs dentro da conta e do espaço de trabalho aos quais o usuário Databricks account tem acesso, use o código de autorização account-level para gerar tokens de acesso no nível account.
- Para chamar REST APIs em apenas um workspace ao qual o usuário account tem acesso, o senhor pode usar o código de autorização de nível workspacepara gerar tokens de acesso no nível workspace apenas para esse workspace.
Gerar um account-level access tokens
-
Use um cliente como
curl
junto com o código de autorização de nível accountpara gerar os tokens de acesso de nível account OAuth . Na seguinte chamadacurl
, substitua os seguintes espaços reservados:- Substitua
<account-id>
pela ID da conta da Etapa 2. - Substitua
<redirect-url>
pelo URL de redirecionamento da Etapa 2. - Substitua
<code-verifier>
pelo verificador de código que você gerou na Etapa 1. - Substitua
<authorization-code>
pelo código de autorização de nível accountque o senhor gerou na Etapa 2.
curl --request POST \
https://accounts.cloud.databricks.com/oidc/accounts/<account-id>/v1/token \
--data "client_id=databricks-cli" \
--data "grant_type=authorization_code" \
--data "scope=all-apis offline_access" \
--data "redirect_uri=<redirect-url>" \
--data "code_verifier=<code-verifier>" \
--data "code=<authorization-code>" - Substitua
-
Na resposta, copie os tokens de acesso account-level OAuth. Os tokens de acesso são as sequências completas de caracteres no objeto
access_token
. Por exemplo, os tokens de acesso na resposta a seguir sãoeyJr...Dkag
:JSON{
"access_token": "eyJr...Dkag",
"refresh_token": "doau...f26e",
"scope": "all-apis offline_access",
"token_type": "Bearer",
"expires_in": 3600
}Esses tokens de acesso expiram em uma hora. Para gerar novos tokens de acesso, repita o procedimento a partir da Etapa 1.
-
Pule para a Etapa 4: Chamar uma API REST da Databricks.
Gerar um workspace-level access tokens
-
Use um cliente como
curl
juntamente com o código de autorização de nível workspacepara gerar os tokens de acesso de nível workspace OAuth . Na seguinte chamadacurl
, substitua os seguintes espaços reservados:- Substitua
<databricks-instance>
pelo Databricks workspace nome da instância, pordbc-a1b2345c-d6e7.cloud.databricks.com
exemplo,. - Substitua
<redirect-url>
pelo URL de redirecionamento da Etapa 2. - Substitua
<code-verifier>
pelo verificador de código que você gerou na Etapa 1. - Substitua
<authorization-code>
pelo código de autorização de nível workspaceque o senhor gerou na Etapa 2.
Bashcurl --request POST \
https://<databricks-instance>/oidc/v1/token \
--data "client_id=databricks-cli" \
--data "grant_type=authorization_code" \
--data "scope=all-apis offline_access" \
--data "redirect_uri=<redirect-url>" \
--data "code_verifier=<code-verifier>" \
--data "code=<authorization-code>" - Substitua
-
Na resposta, copie os tokens de acesso workspace-level OAuth. Os tokens de acesso são as sequências completas de caracteres no objeto
access_token
. Por exemplo, os tokens de acesso na resposta a seguir sãoeyJr...Dkag
:JSON{
"access_token": "eyJr...Dkag",
"refresh_token": "doau...f26e",
"scope": "all-apis offline_access",
"token_type": "Bearer",
"expires_in": 3600
}Esses tokens de acesso expiram em uma hora. Para gerar novos tokens de acesso, repita o procedimento a partir da Etapa 1.
Etapa 4: chamar uma API REST da Databricks
O senhor usa os tokens de acesso account-level ou workspace-level OAuth para se autenticar em Databricks account-level REST APIs e workspace-level REST APIs, dependendo do escopo dos tokens de acesso. O usuário Databricks account deve ser um administrador account para chamar account-level REST APIs.
Exemplo account-level REST API request
Este exemplo usa a autenticação curl
junto com Bearer
para obter uma lista de todos os espaços de trabalho associados a um account.
- Substitua
<oauth-access-token>
pelos tokens de acesso account-level OAuth. - Substitua
<account-id>
pela ID de sua conta.
export OAUTH_TOKEN=<oauth-access-token>
curl --request GET --header "Authorization: Bearer $OAUTH_TOKEN" \
"https://accounts.cloud.databricks.com/api/2.0/accounts/<account-id>/workspaces"
Exemplo workspace-level REST API request
Este exemplo usa curl
junto com a autenticação Bearer
para listar todos os clusters disponíveis no site especificado workspace.
- Substitua
<oauth-access-token>
pelos tokens de acesso account-level ou workspace-level OAuth. - Substitua
<databricks-instance>
pelo Databricks workspace nome da instância, pordbc-a1b2345c-d6e7.cloud.databricks.com
exemplo,.
export OAUTH_TOKEN=<oauth-access-token>
curl --request GET --header "Authorization: Bearer $OAUTH_TOKEN" \
"https://<databricks-instance>/api/2.0/clusters/list"