HttpClient请求开启Kerberos的HTTP服务

小灰灰 2022-11-17 05:24 348阅读 0赞

内容来自 社会我帅神

方案一.

  1. import org.apache.http.HttpResponse;
  2. import org.apache.http.auth.AuthSchemeProvider;
  3. import org.apache.http.auth.AuthScope;
  4. import org.apache.http.auth.Credentials;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.config.AuthSchemes;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpUriRequest;
  9. import org.apache.http.config.Lookup;
  10. import org.apache.http.config.RegistryBuilder;
  11. import org.apache.http.impl.auth.SPNegoSchemeFactory;
  12. import org.apache.http.impl.client.BasicCredentialsProvider;
  13. import org.apache.http.impl.client.CloseableHttpClient;
  14. import org.apache.http.impl.client.HttpClientBuilder;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import javax.security.auth.Subject;
  18. import javax.security.auth.kerberos.KerberosPrincipal;
  19. import javax.security.auth.login.AppConfigurationEntry;
  20. import javax.security.auth.login.Configuration;
  21. import javax.security.auth.login.LoginContext;
  22. import java.io.IOException;
  23. import java.security.Principal;
  24. import java.security.PrivilegedAction;
  25. import java.util.HashMap;
  26. import java.util.HashSet;
  27. import java.util.Set;
  28. public class RequestKerberosUrlUtils {
  29. public static Logger logger = LoggerFactory.getLogger(RequestKerberosUrlUtils.class);
  30. private String principal;
  31. private String keyTabLocation;
  32. public RequestKerberosUrlUtils() {
  33. }
  34. public RequestKerberosUrlUtils(String principal, String keyTabLocation) {
  35. super();
  36. this.principal = principal;
  37. this.keyTabLocation = keyTabLocation;
  38. }
  39. public RequestKerberosUrlUtils(String principal, String keyTabLocation, boolean isDebug) {
  40. this(principal, keyTabLocation);
  41. if (isDebug) {
  42. System.setProperty("sun.security.spnego.debug", "true");
  43. System.setProperty("sun.security.krb5.debug", "true");
  44. }
  45. }
  46. public RequestKerberosUrlUtils(String principal, String keyTabLocation, String krb5Location, boolean isDebug) {
  47. this(principal, keyTabLocation, isDebug);
  48. System.setProperty("java.security.krb5.conf", krb5Location);
  49. }
  50. //模拟curl使用kerberos认证
  51. private static HttpClient buildSpengoHttpClient() {
  52. HttpClientBuilder builder = HttpClientBuilder.create();
  53. Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().
  54. register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  55. builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  56. BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  57. credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
  58. @Override
  59. public Principal getUserPrincipal() {
  60. return null;
  61. }
  62. @Override
  63. public String getPassword() {
  64. return null;
  65. }
  66. });
  67. builder.setDefaultCredentialsProvider(credentialsProvider);
  68. CloseableHttpClient httpClient = builder.build();
  69. return httpClient;
  70. }
  71. public HttpResponse callRestUrl(final String url, final String userId) {
  72. logger.warn(String.format("Calling KerberosHttpClient %s %s %s", this.principal, this.keyTabLocation, url));
  73. Configuration config = new Configuration() {
  74. @SuppressWarnings("serial")
  75. @Override
  76. public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
  77. return new AppConfigurationEntry[]{ new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
  78. AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>() {
  79. {
  80. put("useTicketCache", "false");
  81. put("useKeyTab", "true");
  82. put("keyTab", keyTabLocation);
  83. //Krb5 in GSS API needs to be refreshed so it does not throw the error
  84. //Specified version of key is not available
  85. put("refreshKrb5Config", "true");
  86. put("principal", principal);
  87. put("storeKey", "true");
  88. put("doNotPrompt", "true");
  89. put("isInitiator", "true");
  90. put("debug", "true");
  91. }
  92. })};
  93. }
  94. };
  95. Set<Principal> princ = new HashSet<Principal>(1);
  96. princ.add(new KerberosPrincipal(userId));
  97. Subject sub = new Subject(false, princ, new HashSet<Object>(), new HashSet<Object>());
  98. try {
  99. //认证模块:Krb5Login
  100. LoginContext lc = new LoginContext("Krb5Login", sub, null, config);
  101. lc.login();
  102. Subject serviceSubject = lc.getSubject();
  103. return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
  104. HttpResponse httpResponse = null;
  105. @Override
  106. public HttpResponse run() {
  107. try {
  108. HttpUriRequest request = new HttpGet(url);
  109. HttpClient spnegoHttpClient = buildSpengoHttpClient();
  110. httpResponse = spnegoHttpClient.execute(request);
  111. return httpResponse;
  112. } catch (IOException ioe) {
  113. ioe.printStackTrace();
  114. }
  115. return httpResponse;
  116. }
  117. });
  118. } catch (Exception le) {
  119. le.printStackTrace();
  120. }
  121. return null;
  122. }
  123. }

方案二

  1. package com.post;
  2. import org.apache.http.HttpResponse;
  3. import org.apache.http.auth.AuthSchemeProvider;
  4. import org.apache.http.auth.AuthScope;
  5. import org.apache.http.auth.Credentials;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.config.AuthSchemes;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.client.methods.HttpUriRequest;
  11. import org.apache.http.config.Lookup;
  12. import org.apache.http.config.RegistryBuilder;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.StringEntity;
  15. import org.apache.http.impl.auth.SPNegoSchemeFactory;
  16. import org.apache.http.impl.client.BasicCredentialsProvider;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClientBuilder;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import javax.security.auth.Subject;
  22. import javax.security.auth.login.Configuration;
  23. import javax.security.auth.login.LoginContext;
  24. import javax.security.auth.login.LoginException;
  25. import java.io.IOException;
  26. import java.security.Principal;
  27. import java.security.PrivilegedAction;
  28. public class RequestKerberosUrlUtilsClassPath {
  29. public static Logger logger = LoggerFactory.getLogger(RequestKerberosUrlUtilsClassPath.class);
  30. public RequestKerberosUrlUtilsClassPath() {
  31. }
  32. public RequestKerberosUrlUtilsClassPath(boolean isDebug) {
  33. if (isDebug) {
  34. System.setProperty("sun.security.spnego.debug", "true");
  35. System.setProperty("sun.security.krb5.debug", "true");
  36. }
  37. }
  38. public RequestKerberosUrlUtilsClassPath(String krb5Location, boolean isDebug) {
  39. System.setProperty("java.security.krb5.conf", krb5Location);
  40. }
  41. //模拟curl使用kerberos认证
  42. private static HttpClient buildSpengoHttpClient() {
  43. HttpClientBuilder builder = HttpClientBuilder.create();
  44. Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().
  45. register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
  46. builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
  47. BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  48. credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
  49. @Override
  50. public Principal getUserPrincipal() {
  51. return null;
  52. }
  53. @Override
  54. public String getPassword() {
  55. return null;
  56. }
  57. });
  58. builder.setDefaultCredentialsProvider(credentialsProvider);
  59. CloseableHttpClient httpClient = builder.build();
  60. return httpClient;
  61. }
  62. public HttpResponse get(final String url) {
  63. try {
  64. Subject serviceSubject = getSubject();
  65. return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
  66. HttpResponse httpResponse = null;
  67. @Override
  68. public HttpResponse run() {
  69. try {
  70. HttpUriRequest request = new HttpGet(url);
  71. HttpClient spnegoHttpClient = buildSpengoHttpClient();
  72. httpResponse = spnegoHttpClient.execute(request);
  73. return httpResponse;
  74. } catch (IOException ioe) {
  75. ioe.printStackTrace();
  76. }
  77. return httpResponse;
  78. }
  79. });
  80. } catch (Exception le) {
  81. le.printStackTrace();
  82. }
  83. return null;
  84. }
  85. public HttpResponse post(final String url, final String params) {
  86. try {
  87. Subject serviceSubject = getSubject();
  88. return Subject.doAs(serviceSubject, new PrivilegedAction<HttpResponse>() {
  89. HttpResponse httpResponse = null;
  90. @Override
  91. public HttpResponse run() {
  92. try {
  93. HttpPost httpPost = new HttpPost();
  94. httpPost.setEntity(new StringEntity(params, ContentType.APPLICATION_JSON));
  95. HttpClient spnegoHttpClient = buildSpengoHttpClient();
  96. httpResponse = spnegoHttpClient.execute(httpPost);
  97. return httpResponse;
  98. } catch (IOException ioe) {
  99. ioe.printStackTrace();
  100. }
  101. return httpResponse;
  102. }
  103. });
  104. } catch (Exception le) {
  105. le.printStackTrace();
  106. }
  107. return null;
  108. }
  109. private Subject getSubject() throws LoginException {
  110. String property = System.getProperty("java.security.auth.login.config");
  111. if (null != property) {
  112. Configuration configuration = Configuration.getConfiguration();
  113. //认证模块:Krb5Login
  114. LoginContext lc = new LoginContext("Krb5Login", null, null, configuration);
  115. lc.login();
  116. return lc.getSubject();
  117. }
  118. return new Subject();
  119. }
  120. }

验证

  1. package com.post;
  2. import org.apache.commons.io.IOUtils;
  3. import org.apache.http.HttpResponse;
  4. import java.io.InputStream;
  5. import java.nio.charset.StandardCharsets;
  6. import java.util.Arrays;
  7. public class RequestKerberosUrlUtilsTest {
  8. public static void main(String[] args) {
  9. params();
  10. classPath();
  11. }
  12. public static void params() {
  13. String user = "ws@HENGHE.COM";
  14. String keytab = "D:\\ysstest\\post\\src\\main\\resources\\ws.keytab";
  15. String krb5Location = "D:\\ysstest\\post\\src\\main\\resources\\krb5.conf";
  16. try {
  17. RequestKerberosUrlUtils restTest = new RequestKerberosUrlUtils(user, keytab, krb5Location, false);
  18. // refer to https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Open_and_Read_a_File
  19. String url_liststatus = "http://localhost:8083/offset/test";
  20. // location
  21. HttpResponse response = restTest.callRestUrl(url_liststatus, user);
  22. InputStream is = response.getEntity().getContent();
  23. System.out.println("Status code " + response.getStatusLine().getStatusCode());
  24. System.out.println("message is :" + Arrays.deepToString(response.getAllHeaders()));
  25. System.out.println("string:\n" + new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8));
  26. } catch (Exception exp) {
  27. exp.printStackTrace();
  28. }
  29. }
  30. public static void classPath() {
  31. String krb5Location = "D:\\ysstest\\post\\src\\main\\resources\\krb5.conf";
  32. System.setProperty("java.security.auth.login.config", "D:\\ysstest\\post\\src\\main\\resources\\http.conf");
  33. System.setProperty("java.security.krb5.conf", "D:\\ysstest\\post\\src\\main\\resources\\krb5.conf");
  34. try {
  35. RequestKerberosUrlUtilsClassPath restTest = new RequestKerberosUrlUtilsClassPath();
  36. // refer to https://hadoop.apache.org/docs/stable/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Open_and_Read_a_File
  37. String url_liststatus = "http://localhost:8083/offset/test";
  38. // location
  39. HttpResponse response = restTest.get(url_liststatus);
  40. InputStream is = response.getEntity().getContent();
  41. System.out.println("Status code " + response.getStatusLine().getStatusCode());
  42. System.out.println("message is :" + Arrays.deepToString(response.getAllHeaders()));
  43. System.out.println("string:\n" + new String(IOUtils.toByteArray(is), StandardCharsets.UTF_8));
  44. } catch (Exception exp) {
  45. exp.printStackTrace();
  46. }
  47. }
  48. }

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ambari开启kerberos

    网上一些跟[Ambari启用Kerberos][Ambari_Kerberos],看似很简单,但实际按照这个配置,遇到的问题连解决方案都不好找。启用了kerberos,想要也没