001/*
002 * Copyright (C) 2022-present The Prometheus jmx_exporter Authors
003 *
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 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
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 */
016
017package io.prometheus.jmx.common.http.authenticator;
018
019import com.sun.net.httpserver.BasicAuthenticator;
020import io.prometheus.jmx.common.util.Precondition;
021
022/** Class to implement a username / plaintext password BasicAuthenticator */
023public class PlaintextAuthenticator extends BasicAuthenticator {
024
025    private final String username;
026    private final String password;
027
028    /**
029     * Constructor
030     *
031     * @param realm realm
032     * @param username username
033     * @param password password
034     */
035    public PlaintextAuthenticator(String realm, String username, String password) {
036        super(realm);
037
038        Precondition.notNullOrEmpty(username);
039        Precondition.notNullOrEmpty(password);
040
041        this.username = username;
042        this.password = password;
043    }
044
045    /**
046     * called for each incoming request to verify the given name and password in the context of this
047     * Authenticator's realm. Any caching of credentials must be done by the implementation of this
048     * method
049     *
050     * @param username the username from the request
051     * @param password the password from the request
052     * @return <code>true</code> if the credentials are valid, <code>false</code> otherwise.
053     */
054    @Override
055    public boolean checkCredentials(String username, String password) {
056        return this.username.equals(username) && this.password.equals(password);
057    }
058}