使用JAX-RS进行抢先认证?

时间:2014-08-22 21:11:05

标签: java authentication client jax-rs preemptive

我是一位长期读者和第一次使用的用户,所以请放轻松。

我试图在javax.ws.rs.client.Client中使用preemptive auth。我已经使用了HTTPClient,但我无法弄清楚如何使用JAX身份验证器完成相同的工作。

    HttpClient client = new HttpClient();
    client.getParams().setAuthenticationPreemptive(true);
    Credentials creds = new UsernamePasswordCredentials("user", "pass");
    client.getState().setCredentials(AuthScope.ANY, creds);

我有基本的auth使用JAX。这是我的客户:

    public HttpsConnection() {
        // configure ssl
        final SslConfigurator sslConfig = SslConfigurator.newInstance().keyStoreFile(keyStore).keyPassword("pass");

        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        final SSLContext sslContext = sslConfig.createSSLContext();

        // configure client
        final Client client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(hostnameVerifier)
            .register(new Authenticator(username, password)).register(JacksonFeature.class)
            .register(new JsonObjectMapper()).build();

        WebTarget target = client.target(base_url);
    }

这是我的身份验证过滤器:

public class Authenticator implements ClientRequestFilter {

    private final String user;
    private final String password;

    public Authenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public void filter(ClientRequestContext requestContext) throws IOException {
        MultivaluedMap<String, Object> headers = requestContext.getHeaders();
        final String basicAuthentication = getBasicAuthentication();
        headers.add("Authorization", basicAuthentication);
    }

    private String getBasicAuthentication() {
        String token = this.user + ":" + this.password;
        try {
            return "Basic " + DatatypeConverter.printBase64Binary(token.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new IllegalStateException("Cannot encode with UTF-8", ex);
        }
    }
}

任何人都可以使用带有抢占式身份验证的UsernamePasswordCredentials给我一个示例,就像我在上面使用HTTPClient一样吗?我必须谷歌搜索所有错误的东西,因为我无法找到一个例子。

如果我的帖子完全糟糕,请在OP =)之前通知我。

0 个答案:

没有答案