/*
Copyright 2022 Alibaba Cloud.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.aliyun.arms.unifydemo.unifydemo;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
/**
* @author XX
* @version V1.0.0
* @dept XX-XX
* @date 2025/7/2 16:10
* @description
*/
public class GrafanaIframeUrlGenerator {
private static final String signInHost = "https://signin.aliyun.com";
private static final String loginUrl = "https://www.aliyun.com";
private static final String loginUri = "/federation?Action=Login&LoginUrl=%s&Destination=%s&SigninToken=%s";
private static final String signInTokenUri = "/federation?Action=GetSigninToken&AccessKeyId=%s&AccessKeySecret=%s&SecurityToken=%s&TicketType=%s";
public static void main(String[] args) {
try {
//請根據自己帳號角色情況自行設定,Grafana地址虛商需要加4service
String destination = "https://gnew4servims.console.alibabacloud.com/d/1098370038******-53945-422/ack-pro-apiserver?orgId=9&refresh=60s";
String regionId = "cn-hangzhou";//請自行設定
String accessKey = ""; //請根據自己帳號角色情況自行設定,帳號需要有STS許可權 AliyunSTSAssumeRoleAccess
String secretKey = "";//請根據自己帳號角色情況自行設定
//注意:請根據自己帳號角色情況自行設定,角色需要有讀許可權 AliyunARMSReadOnlyAccess 角色許可權不足會無法訪問
String role="acs:ram::109837003******:role/armsreadonlyforgrafanaiframe";
/*
* 第一步
* */
//設定參數,指定角色ARN,並設定Policy以進一步限制STS Token擷取的權 // acs:ram::$accountID:role/$roleName
//構建AssumeRole請求
AssumeRoleResponse.Credentials key = getCredentials(regionId, accessKey, secretKey, role, "role-" + System.currentTimeMillis());
/*
* 第二步
* 擷取登入Token
* */
String token = getLoginToken(key, destination);
/*
* 第三步
* 擷取免登地址
* */
String url = getUrl(token, destination);
/*
* 第四步
* 跳轉地址
* */
System.out.println(url);
} catch (Error e) {
e.printStackTrace();
}
}
private static AssumeRoleResponse.Credentials getCredentials(String regionId, String accessKey, String secretKey, String roleArn, String roleSessionName) {
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, secretKey);
IAcsClient client = new DefaultAcsClient(profile);
AssumeRoleRequest request = new AssumeRoleRequest();
request.setSysMethod(MethodType.POST);
request.setRoleArn(roleArn);
request.setRoleSessionName(roleSessionName);
request.setDurationSeconds(3600L);
try {
AssumeRoleResponse response = client.getAcsResponse(request);
return response.getCredentials();
} catch (Exception e) {
throw new RuntimeException("AssumeRoleService load ErrCode:" + e.getMessage());
}
}
public static String getLoginToken(AssumeRoleResponse.Credentials key, String destination) {
String token = "";
if (key == null) {
return "";
}
String ticketType = "normal";
if (destination == null || destination.trim().length() == 0 || destination.contains("4service")) {
ticketType = "mini";
}
String signInTokenUrl = "";
try {
signInTokenUrl = signInHost + String.format(signInTokenUri,
URLEncoder.encode(key.getAccessKeyId(), "utf-8"),
URLEncoder.encode(key.getAccessKeySecret(), "utf-8"),
URLEncoder.encode(key.getSecurityToken(), "utf-8"),
URLEncoder.encode(ticketType, "utf-8"));
} catch (Exception e) {
throw new RuntimeException("SigninTokenService build signInTokenUrl error:" + e.getMessage());
}
final CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet signInGet = new HttpGet(signInTokenUrl);
HttpResponse httpResponse = httpClient.execute(signInGet);
String signInToken = "";
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("SigninTokenService failed to retrieve signInToken!");
}
String signInRes = EntityUtils.toString(httpResponse.getEntity());
signInToken = JSON.parseObject(signInRes).getString("SigninToken");
if (signInToken == null) {
throw new RuntimeException("SigninTokenService signInToken is empty while signInRes is:" + signInRes);
}
return signInToken;
} catch (Exception e) {
throw new RuntimeException("SigninTokenService get signInToken error:" + e.getMessage());
}
}
public static String getUrl(String token, String destination) {
String url = "";
try {
url = signInHost + String.format(loginUri,
URLEncoder.encode(loginUrl, "utf-8"),
URLEncoder.encode(destination, "utf-8"),
URLEncoder.encode(token, "utf-8"));
} catch (Exception e) {
throw new RuntimeException("SigninUrlService build getUrl error:" + e.getMessage());
}
return url;
}
}