Basic Authentication with Resteasy client

后端 未结 4 958
囚心锁ツ
囚心锁ツ 2021-02-20 05:57

I\'m trying to perform an basic auth to the login-module which runs on my jboss using REST. I already found an StackOverflow topic which explains how to authenticate with creden

4条回答
  •  天命终不由人
    2021-02-20 06:38

    I recently upgraded to resteasy-client:4.0.0.Final to deal with some Jackson upgrade issues, and I noticed that setting headers seem to work differently (I was getting 401: Authorization Errors for every authenticated request that previously worked). I also couldn't find much documentation, (the 4.0.0.Final release is only a month old and has some dependency issues, if my experience is representative of the broader case).

    The code previously injected headers into the ClientRequestContext:

    public AddAuthHeadersRequestFilter(String username, String password) {
            this.username = username;
            this.password = password;
        }
    
        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            String token = username + ":" + password;
            String base64Token = Base64.encodeString(token);
            requestContext.getHeaders().add("Authorization", "Basic " + base64Token);
        }
    }
    

    then we set the filter on the ResteasyClient like so:

    ResteasyClient client = new ResteasyClientBuilder()
                .sslContext(buildSSLContext())
                .hostnameVerifier(buildHostVerifier())
                .build();
    
    client.register(new AddAuthHeadersRequestFilter(user, pass));
    

    However, this appears not to set the HeaderDelegate, which is where headers are retrieved in 4.x(?) and possibly earlier versions.

    The trick was to register that filter on the ResteasyWebTarget instead of the client in the 4.0.0.Final version (you may notice the clientBuilder works a little differently now too).

        ResteasyClient client = (ResteasyClient)ResteasyClientBuilder.newBuilder()
                .sslContext(buildSSLContext())
                .hostnameVerifier(buildHostVerifier())
                .build();
    
        ResteasyWebTarget target = client.target(url);
    
        target.register(new AddAuthHeadersRequestFilter(user, pass));
    

提交回复
热议问题