Estos contenidos se han traducido de forma automática para su comodidad, pero Huawei Cloud no garantiza la exactitud de estos. Para consultar los contenidos originales, acceda a la versión en inglés.
Centro de ayuda/
Identity and Access Management/
Guía del usuario/
Broker de identidades personalizado/
Creación de un FederationProxyUrl mediante un token
Actualización más reciente 2024-07-30 GMT+08:00
Creación de un FederationProxyUrl mediante un token
En esta sección se proporciona un ejemplo de código utilizado para crear un FederationProxyUrl mediante un token para iniciar sesión en los servicios de Huawei Cloud.
Ejemplo de código usando Java
El siguiente código Java muestra cómo crear un FederationProxyUrl que da a los usuarios federados acceso directo a la consola de Huawei Cloud.
import java.net.URLEncoder; import java.util.Collections; import com.huaweicloud.sdk.core.auth.GlobalCredentials; import com.huaweicloud.sdk.core.http.HttpConfig; import com.huaweicloud.sdk.core.exception.*; import com.huaweicloud.sdk.iam.v3.IamClient; import com.huaweicloud.sdk.iam.v3.model.*; // Use the global domain name to obtain a loginToken. String endpoint = "https://iam.myhuaweicloud.com"; // Configure client attributes. HttpConfig config = HttpConfig.getDefaultHttpConfig() .withIgnoreSSLVerification(true) .withProxyHost("proxy.huawei.com") .withProxyPort(8080); // Use the domain ID (account ID), AK, and SK of userB to initialize the specified IAM client "{Service}Client". For details about how to create userB, see section "Creating an IAM User". IamClient iamClient = IamClient.newBuilder().withCredential(new GlobalCredentials() .withDomainId(domainId) .withAk(ak) .withSk(sk)) .withEndpoint(endpoint) .withHttpConfig(config) .build(); /*CreateTemporaryAccessKeyByToken Call the API used to obtain a temporary access key and securityToken with a token. The default validity period of an access key and securityToken is 900 seconds, that is, 15 minutes. The value ranges from 15 minutes to 24 hours. In this example, the validity period is set to 3600 seconds, that is, 1 hour. When you obtain a loginToken with a specified validity period, ensure that the validity period of the loginToken is not greater than the remaining validity period of the securityToken. */ TokenAuthIdentity tokenAuthIdentity = new TokenAuthIdentity().withMethods(Collections.singletonList(TokenAuthIdentity.MethodsEnum.fromValue("token"))).withToken(new IdentityToken().withDurationSeconds(3600)); CreateTemporaryAccessKeyByTokenRequestBody createTemporaryAccessKeyByTokenRequestBody = new CreateTemporaryAccessKeyByTokenRequestBody().withAuth(new TokenAuth().withIdentity(tokenAuthIdentity)); CreateTemporaryAccessKeyByTokenResponse createTemporaryAccessKeyByTokenResponse = iamClient.createTemporaryAccessKeyByToken(new CreateTemporaryAccessKeyByTokenRequest().withBody(createTemporaryAccessKeyByTokenRequestBody)); Credential credential = createTemporaryAccessKeyByTokenResponse.getCredential(); /*CreateLoginToken Obtain a loginToken. LoginTokens are issued to users to log in through custom identity brokers. Each loginToken contains identity and session information of a user. To log in to a cloud service console using a custom identity broker URL, call this API to obtain a loginToken for authentication. The default validity period of a loginToken is 600 seconds, that is, 10 minutes. The value ranges from 10 minutes to 12 hours. In this example, the validity period is set to 1800 seconds, that is, half an hour. Ensure that the validity period of the loginToken is not greater than the remaining validity period of the securityToken. */ CreateLoginTokenRequestBody createLoginTokenRequestBody = new CreateLoginTokenRequestBody(). withAuth(new LoginTokenAuth().withSecuritytoken(new LoginTokenSecurityToken(). withAccess(credential.getAccess()). withId(credential.getSecuritytoken()). withSecret(credential.getSecret()).withDurationSeconds(1800))); CreateLoginTokenResponse createLoginTokenResponse = iamClient.createLoginToken(new CreateLoginTokenRequest().withBody(createLoginTokenRequestBody)); String loginToken = createLoginTokenResponse.getXSubjectLoginToken(); // Obtain a custom identity broker URL. String authURL = "https://auth.huaweicloud.com/authui/federation/login"; // Login URL of an enterprise management system. String enterpriseSystemLoginURL = "https://example.com/"; // HUAWEI CLOUD service address to access. String targetConsoleURL = "https://console.huaweicloud.com/iam/?region=cn-north-4"; // Create a FederationProxyUrl and return it to the browser through Location. String FederationProxyUrl = authURL + "?idp_login_url=" + URLEncoder.encode(enterpriseSystemLoginURL, "UTF-8") + "&service=" + URLEncoder.encode(targetConsoleURL, "UTF-8") + "&logintoken=" +URLEncoder.encode(loginToken, "UTF-8");
Ejemplo de código usando Python
El siguiente código de Python muestra cómo crear un FederationProxyUrl que da a los usuarios federados acceso directo a la consola de Huawei Cloud.
from huaweicloudsdkcore.auth.credentials import GlobalCredentials from huaweicloudsdkcore.http.http_config import HttpConfig from huaweicloudsdkiam.v3 import * import urllib # Use the global domain name to obtain a loginToken. endpoint = "https://iam.myhuaweicloud.com" # Configure client attributes. config = HttpConfig.get_default_config() config.ignore_ssl_verification = True config.proxy_protocol = "https" config.proxy_host = "proxy.huawei.com" config.proxy_port = 8080 credentials = GlobalCredentials(ak, sk, domain_id) # Use the domain ID (account ID), AK, and SK of userB to initialize the specified IAM client "{Service}Client". For details about how to create userB, see section "Creating an IAM User". client = IamClient().new_builder(IamClient) \ .with_http_config(config) \ .with_credentials(credentials) \ .with_endpoint(endpoint) \ .build() # CreateTemporaryAccessKeyByToken # Call the API used to obtain a temporary access key and securityToken with a token. # The default validity period of an access key and securityToken is 900 seconds, that is, 15 minutes. The value ranges from 15 minutes to 24 hours. In this example, the validity period is set to 3600 seconds, that is, 1 hour. # When you obtain a loginToken with a specified validity period, ensure that the validity period of the loginToken is not greater than the remaining validity period of the securityToken. identity_methods = ["token"] identity_token = IdentityToken(duration_seconds=3600) body = CreateTemporaryAccessKeyByTokenRequestBody( TokenAuth(TokenAuthIdentity(methods=identity_methods, token=identity_token))) request = CreateTemporaryAccessKeyByTokenRequest(body) create_temporary_access_key_by_token_response = client.create_temporary_access_key_by_token(request) credential = create_temporary_access_key_by_token_response.credential # CreateLoginToken # Obtain a loginToken. # LoginTokens are issued to users to log in through custom identity brokers. Each loginToken contains identity and session information of a user. # To log in to a cloud service console using a custom identity broker URL, call this API to obtain a loginToken for authentication. # The default validity period of a loginToken is 600 seconds, that is, 10 minutes. The value ranges from 10 minutes to 12 hours. In this example, the validity period is set to 1800 seconds, that is, half an hour. # Ensure that the validity period of the loginToken is not greater than the remaining validity period of the securityToken. login_token_security_token = LoginTokenSecurityToken(access=credential.access, secret=credential.secret, id=credential.securitytoken, duration_seconds=1800) body = CreateLoginTokenRequestBody(LoginTokenAuth(login_token_security_token)) request = CreateLoginTokenRequest(body) create_login_token_response = client.create_login_token(request) login_token = create_login_token_response.x_subject_login_token # Login URL of the custom identity broker auth_URL = "https://auth.huaweicloud.com/authui/federation/login" # Login URL of an enterprise management system. enterprise_system_login_URL = "https://example.com/" # HUAWEI CLOUD service address to access. target_console_URL = "https://console.huaweicloud.com/iam/?region=cn-north-4" # Create a FederationProxyUrl and return it to the browser through Location. FederationProxyUrl = auth_URL + "?idp_login_url=" + urllib.parse.quote( enterprise_system_login_URL) + "&service=" + urllib.parse.quote( target_console_URL) + "&logintoken=" + urllib.parse.quote(login_token) print(FederationProxyUrl)
Tema principal: Broker de identidades personalizado
Comentarios
¿Le pareció útil esta página?
Deje algún comentario
Muchas gracias por sus comentarios. Seguiremos trabajando para mejorar la documentación.
El sistema está ocupado. Vuelva a intentarlo más tarde.