티스토리 뷰

반응형

REST API 서버로 요청을 보낼 때 아이디와 비밀번호를 이용한 기본 인증(Basic Authentication)이 요구될 수 있다. 터미널에서 curl 명령을 이용해서 REST API를 사용할 때 -u 옵션으로 아이디와 비밀번호를  입력할 수 있다.

curl -u userId:userPassword {...}

 

Basic Authentication 기능을 요구하는 REST API 서버에 OkHttp 클라이언트를 사용해서 요청을 전송하는 예제를 살펴보자.

 

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

 

Java 8 기준으로 작성된 코드라 Java 7 에서는 람다 대신 익명 클래스를 사용하면 된다.

 

OkHttpClient에 Authenticator 적용

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

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

 

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

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함