我在BigQuery中有一些数据。我希望能够使用带有用户输入和控件的网页来动态查询此数据。例如,用户可以从下拉菜单中选择一些选项,然后继续构建一个SQL查询,该查询将在REST请求中发送给BigQuery API。
我正在尝试找出如何简化和/或删除使用API进行这些请求所需的授权。我不希望用户必须使用其Google帐户登录才能授权API请求-该网站将面向内部,并且访问已通过GCP上的身份识别代理进行了控制。问题似乎是我要使用的BQ API(https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query)中的方法需要我必须通过进行用户登录才能获得的授权范围。
我显然已经为请求提供了API密钥和客户端ID-为什么还需要用户登录授权?
<script>
var results;
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/bigquery https://www.googleapis.com/auth/bigquery.readonly https://www.googleapis.com/auth/cloud-platform https://www.googleapis.com/auth/cloud-platform.read-only"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
gapi.client.setApiKey("KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/bigquery/v2/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.bigquery.jobs.query({
"projectId": "PROJECT-ID",
"prettyPrint": true,
"alt": "json",
"resource": {
"query": "SELECT * FROM `TABLE` where Division = 'ERLT Local (Majors)' LIMIT 100",
"location": "europe-west2",
"useLegacySql": false,
"kind": "bigquery#queryRequest"
}
})
.then(function(response) {
var results = response.result.rows;
console.log(results);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: "CLIENT-ID.apps.googleusercontent.com"});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
如上所述,用户必须先单击授权并加载按钮,然后才能执行查询。如何删除此步骤?
我希望能够使用带有用户输入和控件的网页来动态查询此数据。
可以在使用GCP服务帐户访问BQ的网络服务器周围构建所需的功能。可以通过UI或使用以下命令创建帐户:
gcloud iam service-accounts create <sa-name> --display-name "<sa-name>" --description "Service account for BQ read-only access"
然后授予服务帐户运行作业的权限:
gcloud projects add-iam-policy-binding <project-name> --member=serviceAccount:<sa-name>@<project-name>.iam.gserviceaccount.com --role roles/bigquery.jobUser
替换占位符:<sa-name>
-替换为服务帐户名称,<project-name>
-替换为项目名称。
请注意,服务帐户将需要其他权限才能读取数据集。
此solution允许将参数化查询嵌入到Web服务器中。最终用户使用浏览器可以选择设置查询参数,运行查询并检索结果。我是作者。
我不希望用户必须使用其Google帐户登录
用户不必具有GCP帐户。网络服务器使用服务帐户。
例如,用户可以从下拉菜单中选择一些选项,然后继续构建SQL查询
这就是解决方案的作用。但是,出于成本和安全性考虑,最终用户仅允许构造查询的WHERE
子句。您可以修改代码以具有多个SQL查询,然后使用一个下拉列表可以选择要使用的查询,另一个下拉列表可以设置一些查询选项,等等。