I have a BE Java Service, which is RESTFul, which is ported on WSO2 API Manager. It is published and available in Store. I have registered a new Application (by Name ' Java App ') and upon subscribing to that API, it provided me with Client Key and Client Secret along with Token. Using the Token I am able to successfully access the API (from SOAP UI). My requirement is to access the API from a standalone Java Application. Can someone direct me or provide appropriate code that can access the published API.
Regards, Sreedhar.
You can use Apache HTTP client to invoke the API by sending Authorization as a HTTP Header.
String url = "API_URL";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
// add Authorization Header header
request.addHeader("Authorization", "Bearer :" + accessToken);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
For Generating Token with username, password and Client Key / Secret, You can use following cURL sample to build the HTTP request. More information can be found in token api
curl -k -d "grant_type=password&username=<username>&password=<password>" -H "Authorization: Basic SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVzhh" -H "Content-Type: application/x-www-form-urlencoded" https://localhost:8243/token
You have to base 64 encode Client Key / Secret and send it with Authorization header as Basic.
Related
I am working with c++11, beast library and IBM speech to text web service.
The websocket interface (to connect) needs the authentication token as request header while the handshake is performed.
Refering to this code available in the Watson documents it looks like I have to pass the model type (if I want to) as request header too
var IAM_access_token = '{access_token}';
var wsURI = 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize'
+ '?access_token=' + IAM_access_token
+ '&model=es-ES_BroadbandModel';
var websocket = new WebSocket(wsURI);
Also there is a curl request format mentioned to set the "model"
curl -X POST -u "apikey:{apikey}"
--header "Content-Type: audio/flac"
--data-binary #{path}audio-file.flac
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?model=en-US_NarrowbandModel"
Can someone hel me figure out How do I pass "model" in my websocket (using beast in c++11)?
Here is how I am passing the authentication token:
mWebSocket.async_handshake_ex(mHost, "/speech-to-text/api/v1/recognize",
[mToken](request_type& reqHead) {
reqHead.insert(http::field::authorization,mToken);},
bind(&IbmWebsocketSession::send_start, shared_from_this(), placeholders::_1));
As #ALanBirtles suggested
Putting the resuired model in the url as
mWebSocket.async_handshake_ex(mHost, "/speech-to-text/api/v1/recognize?model=en-US_NarrowbandModel",...
Works
I've created an API using WSO2 Api Manager and gave a backend application URL as a production URL. I'm getting 200 response code and Json responce body in web console of the API but when I use JAVA SDK of that API using client. I'm not able to get the response data even though I'm getting 200 response code.
The below mention java code I'm using to consume the API.
Thanks in Advance!
DefaultApi defaultApiTest = new DefaultApi();
ApiClient apiClient = defaultApi.getApiClient();
apiClient.addDefaultHeader("Accept", "application/json");
apiClient.addDefaultHeader("authorization", "Bearer " + "e88aa28a-4e0e-34a1-aec1-55616bf1e7a1");
apiClient.setBasePath("<Production URL of the API>");
defaultApiTest.setApiClient(apiClient);
ApiResponse<?> response = defaultApiTest.getWithHttpInfo();
if(null != response){
JSON data = apiClient.getJSON();
String value = data.toString();
System.out.println(value);
}
I am trying to call MSCRM 365 web services using SOAPUI, this is what i have done so far
Downloaded Organization WSDL from my cRM instance
Uploaded in SOAPUI
Added three header parameters - Content-Type, SOAPAction and Accept
Added Username and Password in Request Properties
Whenever I send a request to MSCRM, I get "HTTP ERROR 401 - Unauthorized: Access is denied"
Anyone have any ideas?
Thanks,
Nitesh
Since this is Dynamics 365 it does not authenticate using Username / Password. Instead you will need to use OAuth as shown in the link
https://msdn.microsoft.com/en-us/library/gg327838.aspx
// TODO Substitute your correct CRM root service address,
string resource = "https://mydomain.crm.dynamics.com";
// TODO Substitute your app registration values that can be obtained after you
// register the app in Active Directory on the Microsoft Azure portal.
string clientId = "e5cf0024-a66a-4f16-85ce-99ba97a24bb2";
string redirectUrl = "http://localhost/SdkSample";
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext =
new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = authContext.AcquireToken(resource, clientId, new
Uri(redirectUrl));
Use the access token in message requests:
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
Another options would be to shift from Xrm.Client to Xrm.Tools.Connection. See the example in this site.
https://msdn.microsoft.com/en-us/library/jj602970.aspx
I am using SAML2 Bearer assertion profile to obtain OAuth Tokens form WSO2 API Manager. I have two client applications. In the OAuth Token Revoking process I am using following code,
public static boolean revokeToken(Token token) throws IOException {
//Create connection to the Token endpoint of API manger
URL url = new URL(Config.apiMangerOAuthRevokeURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
String userCredentials = Config.apiMangerClientID+":"+ Config.apiMangerClientSecret;
String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));
basicAuth = basicAuth.replaceAll("\\r|\\n", "");
// Set the consumer-key and Consumer-secret
connection.setRequestProperty("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("token="+token.getAccess_token());
wr.flush();
wr.close();
//Get Response
InputStream iss = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(iss));
String line;
StringBuffer responseString = new StringBuffer();
while ((line = rd.readLine()) != null) {
responseString.append(line);
responseString.append('\r');
}
rd.close();
System.out.println("Revoking Token Mobile-"+token.getAccess_token());
System.out.println("Revoking Response Mobile -"+responseString.toString());
return true
;
}
One client application do the revoking process OK. I tried to invoke API using CURL after revoking, it fails as expected. But the other client application which use same above logic to revoke tokens return well. But the token is valid after revoking. I can use CURL to query the API. What has gone wrong here?
API Manager has caching enabled by default and is set to 15 min. Try disabling it.
I use the following code to obtain access token for my application in Python.
CLIENT_SECRETS = 'client_secrets.json'
MISSING_CLIENT_SECRETS_MESSAGE = "Missing Client Secrets"
FLOW = flow_from_clientsecrets(os.path.join(os.path.dirname(__file__), CLIENT_SECRETS),
scope=['https://www.googleapis.com/auth/drive','https://www.google.com/m8/feeds'],
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage('drive.dat')
credentials = storage.get()
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("drive", "v2", http=http)
But after obtaining the access token, how am I supposed to retrieve gmail contact list using gdata client library of Python? The sample in client library does not use OAuth authentication but another approach.