OAuth 2.0 서비스 호출

등록된 OAuth 클라이언트는 WebSphere® Application Server OAuth 서비스 권한 엔드포인트를 호출하여 액세스 토큰을 요청할 수 있습니다. 또한 등록된 OAuth 클라이언트는 WebSphere Application Server OAuth 서비스 토큰 엔드포인트를 호출하여 액세스 토큰을 요청할 수 있습니다. 그런 다음 클라이언트는 액세스 토큰을 사용하여 WebSphere Application Server에서 보호된 웹 자원을 요청할 수 있습니다.

WebSphere Application Server OAuth 2.0 서비스는 다음 플로우를 지원합니다.

권한 코드 플로우

권한 엔드포인트를 호출하여 권한 코드를 요청하십시오.
OAuth 클라이언트는 해당 클라이언트 ID, 클라이언트 시크릿, 상태, 경로 재지정 URI 및 선택적 범위를 추가하여 자원 소유자나 사용자를 WebSphere Application Server OAuth 2.0 권한 부여 서비스로 경로 재지정합니다.
https://host_name:port_number/oauth2/endpoint/provider_name/authorize
또는
https://host_name:port_number/oauth2/declarativeEndpoint/provider_name/authorize
OAuth 토큰 엔드포인트를 호출하여 액세스 토큰을 요청하십시오.
OAuth 클라이언트는 authorization_code 부여 유형, authorization code, redirect_urlclient_id를 요청 매개변수로 추가하여 WebSphere Application Server OAuth 2.0 토큰 엔드포인트에서 액세스 토큰을 요청합니다.
https://host_name:port_number/oauth2/endpoint/provider_name/token
다음 예제에서는 권한 코드를 사용하여 URI를 생성하고 웹 자원에 액세스하기 위해 액세스 토큰을 사용하는 과정을 보여 줍니다.
String charset = "UTF-8";
String param1 = "code";

if (isAuthorizationCode){
  String query = String.format("response_type=%s&
                               client_id=%s&
                               client_secret=%s&
                               state=%s&
                               redirect_uri=%s&
                               scope=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset),
                               URLEncoder.encode(state, charset),
                               URLEncoder.encode(redirectURI, charset),
                               URLEncoder.encode(scope, charset));
  String s = authorizationEndPoint + "?" + query;
  System.out.println("Visit: " + s + "\nand grant permission");
  System.out.print("Now enter the OAuth code you have received in redirect uri :");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String code = br.readLine();
  param1 = "authorization_code";
  query = String.format("grant_type=%s&
                        code=%s&
                        client_id=%s&
                        client_secret=%s&
                        state=%s&
                        redirect_uri=%s&
                        scope=%s",
                        URLEncoder.encode(param1, charset),
                        URLEncoder.encode(code, charset),
                        URLEncoder.encode(clientId, charset),
                        URLEncoder.encode(clientSecret, charset),
                        URLEncoder.encode(state, charset),
                        URLEncoder.encode(redirectURI, charset),
                        URLEncoder.encode(scope, charset));
  URL url = new URL(tokenEndPoint);
  HttpsURLConnection con = (HttpsURLConnection)url. openConnection();
  con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset="  + charset);
  con.setDoOutput(true);
  con.setRequestMethod("POST");
  OutputStream output = null;
  try {
    output = con.getOutputStream();
    output.write(query.getBytes(charset));
    output.flush();
  		} finally {
    if (output != null) try {
      output.close();
    } catch (IOException logOrIgnore) {}
  }
  con.connect();
  System.out.println("response message is = " + con.getResponseMessage());
  // read the output from the server
  BufferedReader reader = null;
  StringBuilder stringBuilder;
  reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
  stringBuilder = new StringBuilder();
  String line = null;
  try {
    while ((line = reader.readLine()) != null) {
      stringBuilder.append(line + "\n");
    }
  		} finally {
    if (reader != null) try {
      reader.close();
    } catch (IOException logOrIgnore) {}
  }
  String tokenResponse = stringBuilder.toString();
  System.out.println ("response is = " + tokenResponse);
  JSONObject json = JSONObject.parse(tokenResponse);
  if (json.containsKey("access_token")) {
    accessToken = (String)json.get("access_token");
    this.accessToken = accessToken;
  }
  if (json.containsKey("refresh_token")) {
    refreshToken = (String)json.get("refresh_token");
  }
  //sendRequestForAccessToken(query);
  if (accessToken != null) {
    String query = String.format("access_token=%s",
                                 URLEncoder.encode(accessToken, charset));
    URL urlResource = new URL(resourceEndPoint);
    HttpsURLConnection conn = (HttpsURLConnection) urlResource.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    output = null;
    try {
      output = conn.getOutputStream();
      output.write(query.getBytes(charset));
      output.flush();
    		} finally {
      if (output != null) try {
        output.close();
      } catch (IOException logOrIgnore) {}
    }
    conn.connect();
    System.out.println("response to the resource request is = " + conn.getResponseMessage ());
    reader = null;
    if(conn.getResponseCode()>=200 && conn.getResponseCode() < 400) {
      reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      stringBuilder = new StringBuilder();
      String line = null;
      try {
        while ((line = reader.readLine()) != null) {
          stringBuilder.append(line + "\n");
        }
      		} finally {
        if (reader != null) try {
          reader.close();
        } catch (IOException  logOrIgnore) {}
      }
      System.out.println ("response message to the request resource is = " +  stringBuilder.toString());
    } else {
      isValidResponse = false;
    }
  }
}

암시적 부여 플로우

OAuth 클라이언트는 토큰 response_type, redirect_url, client_id, scopestate를 요청 매개변수로 추가하여 WebSphere Application Server OAuth 2.0 권한 엔드포인트에서 액세스 토큰을 요청합니다.
https://host_name:port_number/oauth2/endpoint/provider_name/authorize
또는
https://host_name:port_number/oauth2/declarativeEndpoint/provider_name/authorize
다음 예제에서는 암시적 부여 사용 시 URI를 생성하는 과정을 보여 줍니다.
if (isImplicit) {
  param1 = "token";
  String query = String.format("response_type=%s&
                               client_id=%s&
                               state=%s&
                               redirect_uri=%s&
                               scope=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(state, charset),
                               URLEncoder.encode(redirectURI, charset),
                               URLEncoder.encode(scope, charset));
  String s = authorizationEndPoint + "?" + query;
  System.out.println("Visit: " + s + "\nand grant permission");
  System.out.print("Now enter the access token you have received in redirect uri :");
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  accessToken = br.readLine();
  if (accessToken != null) {
    // send Resource Request using the access token
  }
}

클라이언트 신임 정보 플로우

OAuth 클라이언트는 클라이언트 ID와 클라이언트 비밀번호를 사용하여 토큰 엔드포인트에 액세스하고 차후 자원 요청을 위해 액세스 토큰을 교환합니다. 이 플로우에서 클라이언트는 client_credentials 부여 유형, client_idclient_secret를 요청 매개변수로 추가하여 토큰 엔드포인트에 액세스합니다.
https://host_name:port_number/oauth2/endpoint/provider_name/token
다음 예제에서는 클라이언트 신임 정보 사용 시 URI를 생성하는 과정을 보여 줍니다.
if (isClientCredentials){
  param1 = "client_credentials";
  String query = String.format("grant_type=%s&
                               scope=%s&
                               client_id=%s&
                               client_secret=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(scope, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset));
  accessToken = sendRequestForAccessToken(query);
  if (accessToken != null)	{
    //send Resource Request using (accessToken);
  }
}

자원 소유자 비밀번호 신임 정보 플로우

자원 소유자 비밀번호 신임 정보 플로우는 자원 소유자의 사용자 ID와 비밀번호를 토큰 엔드포인트로 직접 전달합니다. 이 플로우에서 OAuth 클라이언트는 password 부여 유형, client_id, client_secret, username, password, scopestate를 요청 매개변수로 추가하여 토큰 엔드포인트에 액세스합니다.
https://host_name:port_number/oauth2/endpoint/provider_name/token
다음 예제에서는 자원 소유자 비밀번호 사용 시 URI를 생성하는 과정을 보여 줍니다.
if (isResourceOwnerCredentials) {
  param1 = "password";
  String query = String.format("grant_type=%s&
                               username=%s&
                               password=%s&
                               scope=%s&
                               client_id=%s&
                               client_secret=%s",
                               URLEncoder.encode(param1, charset),
                               URLEncoder.encode(resOwnerName, charset),
                               URLEncoder.encode(resOwnerPassword, charset),
                               URLEncoder.encode(scope, charset),
                               URLEncoder.encode(clientId, charset),
                               URLEncoder.encode(clientSecret, charset));
  accessToken = sendRequestForAccessToken(query);
  if (accessToken != null)	{
    //send Resource Request using (accessToken);
  }
}
액세스 토큰이 만료되면 유효한 액세스 토큰을 가져오기 위해 새로 고치기 토큰이 전송될 수 있습니다. 다음 예제에서는 새로 고치기 토큰을 전송하는 방법을 보여 줍니다.
if(isAccessToken) {
  if (this.accessToken != null) {
    if (!sendResourceRequest(this.accessToken)) {
      // resource request failed...
      //get refresh token
      param1 = "refresh_token";
      String query = String.format("grant_type=%s&
                                   client_id=%s&
                                   client_secret=%s&
                                   refresh_token=%s&
                                   scope=%s",
                                   URLEncoder.encode(param1, charset),
                                   URLEncoder.encode(clientId, charset),
                                   URLEncoder.encode(clientSecret, charset),
                                   URLEncoder.encode(this.refreshToken, charset),
                                   URLEncoder.encode(scope, charset));
      accessToken = sendRequestForAccessToken(query);
      if (accessToken != null) {
        sendResourceRequest(accessToken);
      }
    }
  }
}

주제의 유형을 표시하는 아이콘 개념 주제



시간소인 아이콘 마지막 업데이트 날짜: Tuesday, 6 December 2016
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=cwlp_oauth_invoking
파일 이름: cwlp_oauth_invoking.html