001/*
002 * Copyright 2023 the original author or authors.
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * https://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package de.cuioss.portal.restclient;
017
018import java.io.IOException;
019import java.nio.charset.StandardCharsets;
020import java.util.Base64;
021
022import jakarta.ws.rs.client.ClientRequestContext;
023import jakarta.ws.rs.client.ClientRequestFilter;
024import jakarta.ws.rs.core.HttpHeaders;
025
026import lombok.NonNull;
027
028/**
029 * Filter to set basic authentication header.
030 */
031public class BasicAuthenticationFilter implements ClientRequestFilter {
032
033    private final String headerValue;
034
035    public BasicAuthenticationFilter(@NonNull String username, @NonNull String password) {
036        headerValue = "Basic "
037                + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.US_ASCII));
038    }
039
040    @Override
041    public void filter(ClientRequestContext requestContext) throws IOException {
042        requestContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, headerValue);
043
044    }
045}