Query permissions with the Java SDK

Updated at:

You can use the MaxCompute Java SDK to query permission information for specific users, roles, and resources. The results, returned in JSON format, support various integration needs. This topic demonstrates how to perform these queries and provides JSON output examples.

Prerequisites

Install MaxCompute Studio, connect to a MaxCompute project, and create a MaxCompute Java module.

For more information about installing MaxCompute Studio, see Install MaxCompute Studio.

For more information about managing project connections, see Manage project connections.

For more information about creating a MaxCompute Java module, see Create a MaxCompute Java module.

Assume that you have created a project named Project2 and a MaxCompute Java module named mc_java in MaxCompute Studio. After you create the MaxCompute Java module, the project directory structure is as follows:

Project2
├── .idea
├── mc_java
│   ├── examples
│   ├── src
│   │   ├── main
│   │   │   ├── java
│   │   │   └── resources
│   │   └── test
│   │       └── java
│   ├── target
│   ├── mc_java.iml
│   └── pom.xml
├── scripts
├── target
├── warehouse
├── Project2.iml
├── External Libraries
└── Scratches and Consoles

Background

You can run permission query commands in MaxCompute in several ways. Choose the method that best fits your business requirements.

  • Write a Java program by using the Java SDK, which returns permission query results in JSON format. This topic focuses on this method.

  • Run permission query commands by using the MaxCompute client, odpscmd, SQL Analysis, DataWorks, or MaxCompute Studio. The permission query results are displayed in the command-line execution window.

Supported permission queries

Use the Java SDK to query the following permission information in MaxCompute:

  • Query permissions for a user or role in a MaxCompute project.

    • Query permissions for a user or role on non-shared resources within a MaxCompute project. The SQL syntax is as follows:

      show grants for {<user_name>|<role_name>};
      • user_name: Required. The Alibaba Cloud account or RAM user account. To find the account, see View a list of users.

      • role_name: Required. The name of the role. To find the name, see View a list of roles.

    • Query permissions for a user or role on shared resources within a MaxCompute project. The SQL syntax is as follows:

      show grants for {<user_name>|<role_name>} privilegeproperties ("refobject"="true");
      • user_name: Required. The Alibaba Cloud account or RAM user account. To find the account, see View a list of users.

      • role_name: Required. The name of the role. To find the name, see View a list of roles.

  • Query permissions granted on tables or roles in a MaxCompute project.

    • Query ACL-based grants on a specified table. The SQL syntax is as follows:

      show grants on table <table_name>;

      table_name: Required. Specify the name of the table. To find the name, see List tables and views in a project.

    • Query policy-based grants on a specified table. The SQL syntax is as follows:

      show grants on table <table_name> privilegeproperties ("policy"="true");

      table_name: Required. Specify the name of the table. To find the name, see List tables and views in a project.

    • Query ACL permissions for a table in a package that is installed in a MaxCompute project. The SQL syntax is as follows:

      show grants on table <table_name> privilegeproperties ("refobject"="true", "refproject"="<project_name>");
      • table_name: Required. Specify the name of the table. To find the name, see List tables and views in a project.

      • project_name: Required. Specify the name of the MaxCompute project.

    • Query users assigned to a role. The SQL syntax is as follows:

      show principals <role_name>;

      role_name: Required. Specify the name of the role. To find the name, see View a list of roles.

For examples of these permission queries, see Query result examples.

Procedure

  1. Start IntelliJ IDEA. In the top menu bar, choose File > Open and open your project, such as Project2.

  2. In the navigation pane on the left, navigate to src > main > java in the Java module directory. Right-click the java folder and choose New > MaxCompute Java.

  3. Select UDF for the Java Class type, enter a name for the Java Class, such as OdpsSdk, and press Enter.

  4. In the editor, develop the Java program.

    The following is a template for the Java program:

    import com.aliyun.odps.Odps;
    import com.aliyun.odps.OdpsException;
    import com.aliyun.odps.account.Account;
    import com.aliyun.odps.account.AliyunAccount;
    public class <class_name> {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
         		// Using an Alibaba Cloud account's AccessKey poses a high security risk because it grants full API permissions. For better security, create and use a RAM user for API access and daily operations. You can create one in the RAM console.
    				// This example shows how to store the AccessKey ID and AccessKey Secret in environment variables. You can also store them in a configuration file based on your business requirements.
    				// We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your code to prevent key leakage.
            Account account = new AliyunAccount(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            Odps odps = new Odps(account);
            String odpsUrl = "<endpoint>";
            odps.setEndpoint(odpsUrl);
            odps.setDefaultProject("<project_name>");
             try {  
                String out = odps.projects().get("<project_name>").getSecurityManager().runQuery("<SQL>", true); // true indicates that the output is in JSON format.        
                System.out.print("out: " + out + "\n"); // Returns {} on success.
            } catch (OdpsException e) {
                //Exception handling
            }
        }
    }
    • class_name: Required. The name of your Java class. It must match the name you entered in step 3.

    • ALIBABA_CLOUD_ACCESS_KEY_ID: Configure an environment variable with this name to store the AccessKey ID of the Alibaba Cloud account that is used to access the MaxCompute project. You can click AccessKey Management to obtain an AccessKey ID.

    • ALIBABA_CLOUD_ACCESS_KEY_SECRET: Configure an environment variable with this name to store the AccessKey Secret that corresponds to the AccessKey ID.

    • endpoint: Required. The endpoint of the region where the target MaxCompute project is located. For more information about endpoints, see Endpoints.

    • project_name: Required. The name of the target MaxCompute project.

    • SQL: Required. The SQL statement used to query permission information. For the SQL syntax, see Supported permission queries.

    The following code provides a sample Java program:

    import com.aliyun.odps.Odps;
    import com.aliyun.odps.OdpsException;
    import com.aliyun.odps.account.Account;
    import com.aliyun.odps.account.AliyunAccount;
    public class OdpsSdk {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // Using an Alibaba Cloud account's AccessKey poses a high security risk because it grants full API permissions. For better security, create and use a RAM user for API access and daily operations. You can create one in the RAM console.
    				// This example shows how to store the AccessKey ID and AccessKey Secret in environment variables. You can also store them in a configuration file based on your business requirements.
    				// We strongly recommend that you do not hard-code the AccessKey ID and AccessKey Secret in your code to prevent key leakage.
            Account account = new AliyunAccount(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            Odps odps = new Odps(account);
            String odpsUrl = "http://service.cn-hangzhou.maxcompute.aliyun.com/api";
            odps.setEndpoint(odpsUrl);
            odps.setDefaultProject("doc_test_dev");
            try {
                String out = odps.projects().get("doc_test_dev").getSecurityManager().runQuery("show grants for ALIYUN$****@test.aliyunid.com;", true); 
                System.out.print("out: " + out + "\n"); // Returns {} on success.
            } catch (OdpsException e) {
                //Exception handling
            }
        }
    }
  5. In the navigation pane, right-click the newly created Java class and select Run 'class_name.main()' to run the program.

  6. View the permission query results in the script output section at the bottom of the IntelliJ IDEA interface.

    out: {"ProjectOwner": "full-control"}
    Process finished with exit code 0

Query result examples

  • Permissions of a user or role in a MaxCompute project

    • Example 1: Query permissions for a user or role on non-shared resources within a MaxCompute project.

      Sample SQL statement: show grants for ALIYUN$odpstest2@aliyun.com;.

      Command-line output:

      # Roles assigned to ALIYUN$odpstest2@aliyun.com.
      [roles]        
      r1
      # ACL permissions of ALIYUN$odpstest2@aliyun.com.
      Authorization Type: ACL            
      [user/ALIYUN$odpstest2@aliyun.com]
      A    projects/new_priv_prj_1: All
      A    projects/new_priv_prj_1/tables/test_1: All
      # Policy-based permissions of ALIYUN$odpstest2@aliyun.com.
      Authorization Type: Policy        
      [role/r1]
      # A = Allow, C = Condition attached, D = Deny
      AC    projects/new_priv_prj_1/tables/test2: Select  
      # Tables created by ALIYUN$odpstest2@aliyun.com.
      Authorization Type: ObjectCreator 
      # A = Allow, G = Grant permission
      AG    projects/new_priv_prj_1/tables/user_t: All   

      SDK JSON output:

      {
          "ACL": {"user/ALIYUN$odpstest2@aliyun.com": [{
                      "Action": ["All"],
                      "Effect": "",
                      "Resource": ["acs:odps:*:projects/new_priv_prj_1/tables/test_1"]},
                  {
                      "Action": ["All"],
                      "Effect": "",
                      "Resource": ["projects/new_priv_prj_1"]}]},
          "POLICY": {"role/r1": [{
                      "Action": ["odps:Select"],
                      "Condition": {"IpAddress": {"acs:SourceIp": ["10.10.10.10",
                                  "10.10.10.10/4"]}},
                      "Effect": "Allow",
                      "Resource": ["acs:odps:*:projects/new_priv_prj_1/tables/test2"]}]},
          "SuperPrivs": []
      }
    • Example 2: Query permissions for a user or role on shared resources within a MaxCompute project.

      Sample SQL statement: show grants for ALIYUN$odpstest2@aliyun.com privilegeproperties ("refobject" = "true");.

      Command-line output:

      # Roles assigned to ALIYUN$odpstest2@aliyun.com.
      [roles]   
      r1
      # Permissions on shared resources for ALIYUN$odpstest2@aliyun.com.
      Authorization Type: InstalledObjecACL  
      [pkg1_prj1_1]
      A    projects/new_priv_prj_2/tables/prj2_tb1: Select

      SDK JSON output:

      {"SharedObjectACL": {"pkg1_prj1_1": [{
                      "Action": ["Select"],
                      "Effect": "",
                      "Resource": ["acs:odps:*:projects/new_priv_prj_2/tables/prj2_tb1"]}]}}
  • Permissions on a table or role in a MaxCompute project

    • Example 1: Query ACL-based grants on a specified table.

      Sample SQL statement: show grants on table test_1;.

      Command-line output:

      # The grantor is the project owner or the creator of the table test_1.
      Authorization Type: Implicit  
      AG    project_owner/ALIYUN$odpstest1@aliyun.com: All
      AG    object_creator/ALIYUN$odpstest1@aliyun.com: All
      # The user granted permissions on the table test_1 by using an ACL.
      Authorization Type: ACL   
      A    user/ALIYUN$odpstest2@aliyun.com: All

      SDK JSON output:

      {"ACL": {"": [{
                      "Action": ["All"],
                      "Effect": "",
                      "Principal": ["user/ALIYUN$odpstest2@aliyun.com"]}]}}
    • Example 2: Query policy-based grants on a specified table.

      Sample SQL statement: show grants on table test2 privilegeproperties ("policy" = "true");.

      Command-line output:

      # The grantor is the project owner.
      Authorization Type: Implicit
      AG    project_owner/: All
      # The role granted permissions on the table test2 by using a policy.
      Authorization Type: Policy  
      [role/r1]

      SDK JSON output:

      {"POLICY": {"role/r1": [{
                      "Action": ["odps:Select"],
                      "Condition": {"IpAddress": {"acs:SourceIp": ["10.10.10.10",
                                  "10.10.10.10/4"]}},
                      "Effect": "Allow",
                      "Resource": ["acs:odps:*:projects/new_priv_prj_1/tables/test2"]}]}}
    • Example 3: Query ACL-based grants on a table from an installed package.

      Sample SQL statement: show grants on table prj2_tb1 privilegeproperties ("refobject" = "true", "refproject"="new_priv_prj_2");.

      Command-line output:

      # The grantor is the project owner.
      Authorization Type: Implicit
      AG    project_owner/: All
      Authorization Type: InstalledObjecACL
      # The name of the package.
      [pkg1_prj1_1]
      # The user granted permissions by using the package ACL.
      A    user/ALIYUN$odpstest2@aliyun.com: Select

      SDK JSON output:

      {"SharedObjectACL": {"pkg1_prj1_1": [{
                      "Action": ["Select"],
                      "Effect": "",
                      "Principal": ["user/ALIYUN$odpstest2@aliyun.com"]}]}}
    • Example 4: Query users assigned to a role.

      Sample SQL statement: show principals r1;.

      Command-line output:

      # The user assigned to the role.
      ALIYUN$odpstest2@aliyun.com

      SDK JSON output:

      ["ALIYUN$odpstest2@aliyun.com"]