본문 바로가기
카테고리 없음

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

by 왕 달팽이 2020. 3. 13.
반응형

REST API 서버로 요청을 보낼 때 사용자 인증(Authentication)이 요구되는 경우가 있습니다. 가장 기본적인 인증(Basic Authentication)은 아이디와 비밀번호를 통한 인증입니다.

리눅스의 유틸리티 툴인 curl을 이용해 REST 요청을 보내는 경우 -u 옵션으로 아이디와 비밀번호를 입력할 수 있습니다.

curl -u ID:PassWord {...}

이렇게 기본인증(Basic Authencation)을 요구하는 REST API 서버에 OkHttp 클라이언트를 사용해서 요청을 전송하는 예제를 살펴보겠습니다.

OkHttp Basic Authenticatior

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();
    }
}

이 코드는 Java 8을 기준으로 작성되어 있습니다. (람다 사용)

OkHttpClient에 Authenticator 적용

OkHttpClient Builder 클래스에는 Authenticator를 명시할 수 있는 authenticator 메소드가 있습니다. 위에서 작성한 Authenticator 생성 메소드를 다음과 같이 호출해주면 됩니다.

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

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

반응형

댓글