我正在使用 Duo Security Admin API。但是当我使用下面的代码调用 api 时,它显示:
Get Users request failed with HTTP (response code: 401)
这是我的java代码:
void users(){
// Duo Admin API credentials and API hostname
String integrationKey = "DI7ABPU9TUJQO14RET9Q";
String secretKey = "YzDs7ZeQGMllravxDQxcn4jNAwyqF42P1XBDdGd2";
String apiHostname = "api-d221a358.duosecurity.com";
try {
String usersUrl = "https://" + apiHostname + "/admin/v1/users";
// Create URL object
URL url = new URL(usersUrl);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method to GET
connection.setRequestMethod("GET");
// Set request headers
connection.setRequestProperty("Authorization", "Basic " + getBase64Credentials(integrationKey, secretKey));
connection.setRequestProperty("Date", OffsetDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME));
connection.setRequestProperty("Content-Type", "application/json");
// Get the HTTP response code
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read and print the response (list of users)
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println("List of Users: " + response.toString());
}
} else {
System.out.println("Get Users request failed with HTTP response code: " + responseCode);
}
// Close the connection
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
// Encode credentials as Base64
private static String getBase64Credentials(String integrationKey, String secretKey) {
String credentials = integrationKey + ":" + secretKey;
return java.util.Base64.getEncoder().encodeToString(credentials.getBytes());
}
我的代码犯了什么错误? 调用 Duo Security Admin API 的方法正确吗?
请帮助我..
对于获取用户 Duo admin API 适合我的代码是
生成签名代码为
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.codec.binary.Hex;
@Service
@Slf4j
public class GenerateSignature {
public String generateTheToken(List<String> urlArgs, Map<String, String> params, String ikey, String skey) {
String canonicalString = generatecanonicalString(urlArgs,params);
return getAPISignature(canonicalString,ikey,skey);
}
public String generatecanonicalString(List<String> urlArgs, Map<String, String> params)
{
String canonicalString = String.join("\n", urlArgs);
canonicalString+="\n";
String parametersString=params.entrySet().stream().map(entry->entry.getKey()+"="+entry.getValue())
.collect(Collectors.joining("&"));
canonicalString+=parametersString;
System.out.println(canonicalString);
return canonicalString;
}
public String getAPISignature(String url,String ikey,String skey) {
Mac sha1Hmac = null;
try {
sha1Hmac = Mac.getInstance("HmacSHA1");
SecretKeySpec secretKey = new SecretKeySpec(skey.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
sha1Hmac.init(secretKey);
} catch (NoSuchAlgorithmException | InvalidKeyException | IllegalArgumentException e) {
log.error("error in");
return StringUtils.EMPTY;
}
byte[] signatureBytes = sha1Hmac.doFinal(url.getBytes(StandardCharsets.UTF_8));
String signature= Hex.encodeHexString(signatureBytes);
String auth = ikey + ":" + signature;
System.out.println(Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)));
return Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
}
}
获取用户服务等级是
package com.ciscoduo.bulkgenerator.service;
import com.ciscoduo.bulkgenerator.utilies.GenerateSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
public class getUsers {
private SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
private String currentTime = dateFormat.format(new Date());
@Autowired
private GenerateSignature generateSignature;
private RestTemplate restTemplate = new RestTemplate();
public Object getUser() throws Exception {
String ikey = "DIEZT523RM4GZ4ETBJBQ";
String skey = "3z9e75OxFp7TuxzHJDWtctntsp2hu0UlkRgr9VxQ";
String host="api-43c07036.duosecurity.com";
String userspath="/admin/v1/users";
String url = "https://api-43c07036.duosecurity.com/admin/v1/users";
List<String> urlArgs = List.of(currentTime, "GET", host, userspath);
String token = generateSignature.generateTheToken(urlArgs, Map.of(), ikey,skey);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("Authorization", "Basic " + token);
headers.set(HttpHeaders.DATE, currentTime);
HttpEntity<Object> entity = new HttpEntity<>(headers);
ResponseEntity<Object> ciscoDuoResponse = restTemplate.
exchange(url, HttpMethod.GET, entity, Object.class);
System.out.println(ciscoDuoResponse.getBody());
return ciscoDuoResponse.getBody();
}
}
主要课程是
package com.ciscoduo.bulkgenerator;
import com.ciscoduo.bulkgenerator.service.getUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
@SpringBootApplication
public class BulkgeneratorApplication implements CommandLineRunner {
@Autowired
private getUsers getUsers;
public static void main(String[] args) {
SpringApplication.run(BulkgeneratorApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
getUsers.getUser();
}
}