Basic Authentication with Resteasy client

后端 未结 4 1028
囚心锁ツ
囚心锁ツ 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:51

    Consider the solution from Adam Bien:

    You can attach an ClientRequestFilter to the RESTEasy Client, which adds the Authorization header to the request:

    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 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);
            }
        }
    }
    
    Client client = ClientBuilder.newClient()
                         .register(new Authenticator(user, password));
    

提交回复
热议问题