/*
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://gnew4service.console.aliyun.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;
}
}