001/* 002 * Copyright 2020 Vonage 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 */ 016package com.vonage.client.auth; 017 018import com.fasterxml.jackson.databind.ObjectMapper; 019import com.fasterxml.jackson.databind.node.ObjectNode; 020import com.vonage.client.VonageUnexpectedException; 021import org.apache.commons.codec.binary.Base64; 022import org.apache.http.Header; 023import org.apache.http.HttpEntity; 024import org.apache.http.client.methods.RequestBuilder; 025import org.apache.http.entity.ContentType; 026import org.apache.http.entity.StringEntity; 027import org.apache.http.message.BasicHeader; 028import org.apache.http.util.EntityUtils; 029 030import java.io.IOException; 031 032public class TokenAuthMethod extends AbstractAuthMethod { 033 private final int SORT_KEY = 30; 034 035 private String apiKey; 036 private String apiSecret; 037 038 public TokenAuthMethod(String apiKey, String apiSecret) { 039 this.apiKey = apiKey; 040 this.apiSecret = apiSecret; 041 } 042 043 @Override 044 public RequestBuilder apply(RequestBuilder request) { 045 return request.addParameter("api_key", this.apiKey).addParameter("api_secret", this.apiSecret); 046 } 047 048 @Override 049 public RequestBuilder applyAsBasicAuth(RequestBuilder request) { 050 String headerValue = Base64.encodeBase64String((this.apiKey + ":" + this.apiSecret).getBytes()); 051 Header authHeader = new BasicHeader("Authorization", "Basic " + headerValue); 052 return request.addHeader(authHeader); 053 } 054 055 @Override 056 public RequestBuilder applyAsJsonProperties(RequestBuilder request) { 057 HttpEntity entity = request.getEntity(); 058 try { 059 ObjectNode json = (ObjectNode) new ObjectMapper().readTree(EntityUtils.toString(entity)); 060 json.put("api_key", this.apiKey); 061 json.put("api_secret", this.apiSecret); 062 063 return request.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); 064 } catch (IOException e) { 065 throw new VonageUnexpectedException("Failed to attach api key and secret to json.", e); 066 } 067 } 068 069 @Override 070 public int getSortKey() { 071 return SORT_KEY; 072 } 073}