본문 바로가기
Old Posts/Java

[Java] OkHttp id-password를 사용한 기본 인증 예제 (Basic Authentication Example)

by A6K 2021. 4. 21.

자바로 REST API를 사용할 때 OkHttp 라이브러리를 자주 사용한다. REST API 중에는 가장 '기본 인증(Basic Authentication)' 방법으로 사용자의 아이디와 비밀번호를 요구하는 경우가 있다. 

터미널에서 curl 명령으로 REST API를 사용할 때에는 -u 옵션으로 아이디와 비밀번호를 입력할 수 있다.

curl -u userId:userPassword {...}

OkHttp 라이브러리를 사용하는 자바 프로그램에서는 어떻게 '기본 인증(Basic Authentication)'을 요구하는 REST API 서버에 인증을 진행하는지 예제를 통해서 알아보겠다.

BasicAuthenticator 구현

OkHttp 클라이언트는 OkHttp3.Authenticator라는 인터페이스를 구현한 Authenticator를 이용해 인증을 진행할 수 있다. 아이디와 비밀번호를 이용하는 BasicAuthenticator를 얻어오는 메소드는 다음처럼 작성할 수 있다..

private static Authenticator getAuthenticator(fianl String userId, final String password) {

    return (route, response) -> {
        String credential = Credential.basic(userId, password);
        
        return response.request().newBuilder().header("Authorization", credential).build();
    }
}

getAuthenticator() 메소드에 인자로 넘겨준 userId, password 값을 이용하는 Authenticator 람다 함수를 리턴했다. 자바 7 이하 버전에서는 람다 대신 익명 클래스를 사용하면 된다.

BasicAuthenticator 사용

OkHttpClient를 생성할 때, 빌더 클래스에서 authenticator() 메소드를 통해 방금 생성한 BasicAuthenticator를 지정할 수 있다. 위에서 작성한 Authenticator 생성 메소드를 호출해서 userId, password를 사용하도록 OkHttpClient를 설정할 수 있다.

OkHttpClient client = new OkHttpClient.Builder()
    .authenticator(getAuthenticator(userId, password)
    .build();

이렇게 만들어진 OkHttpClient를 이용해서 REST API 서버에 요청을 전송하면 된다.

댓글