【问题标题】:Apache Shiro authcBasic authentication using Java and apache HttpClient使用 Java 和 apache HttpClient 的 Apache Shiro authcBasic 身份验证
【发布时间】:2013-01-30 04:25:11
【问题描述】:

我的 REST 应用程序使用 Shiro 基本身份验证来保护 REST 端点,并且在通过浏览器进行测试时它工作得很好。

现在我希望能够使用 Apache HttpClient 从 java 客户端登录应用程序

有什么想法吗?

谢谢

【问题讨论】:

  • 你想借助java代码通过apache http客户端连接rest webservice吗?
  • 不,我想登录一个需要 Java 的基于表单的身份验证的应用程序
  • 好的,明白了。有趣....
  • HttpClient 有很好的文档,包括如何进行身份验证。看看这里hc.apache.org/httpclient-legacy/authentication.html
  • 我很困惑 - 您使用的是 authcBasic 还是基于表单的身份验证?

标签: java rest httpclient shiro


【解决方案1】:

您可以将 Java URL 与 Authenticator 一起使用

下面是一个使用 Java URL 访问 SVN http 存储库的示例:

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: Omar MEBARKI
 * To change this template use File | Settings | File Templates.
 */
public class URLConfiguration {
    private URL configURL;

    public URLConfiguration(final String login, final String password, String httpURL) throws Exception {
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(login, password.toCharArray());
            }
        });
        this.configURL = new URL(httpURL);
    }

    public Properties getConfiguration() throws Exception {
            Properties props = new Properties();
            props.load(configURL.openStream());
            return props;
        }

}

【讨论】:

    【解决方案2】:

    这对我有用

            DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
    
            httpclient.getCredentialsProvider().setCredentials(
                new AuthScope("localhost", 9009),
                new UsernamePasswordCredentials("username", "password*"));
    
            HttpGet httpget = new HttpGet("http://localhost:9009/path/list");
    
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            System.out.println("executing request" + httpget.getRequestLine());
    
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            System.out.println("----------------------------------------");
            System.out.println("Job Done!");
        } catch (Exception ex) {
            Logger.getLogger(Command.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-28
      • 1970-01-01
      • 2014-12-20
      • 2016-04-02
      • 2014-08-31
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多