I can not connect with AWS iot when I'm going to create new key and certificate.
It gives me error as under:
com.amazonaws.AmazonServiceException: User:
arn:aws:sts::964546574005:assumed-role/Cognito_GTekPool3Unauth_Role/CognitoIdentityCredentials
is not authorized to perform:
iot:CreateKeysAndCertificate on resource: * (Service: AWSIot; Status
Code: 403; Error Code: AccessDeniedException; Request ID:
b1c4acdd-b1ba-11e8-9d83-772e33c0d6b2)
Below is what I have done in code:
if (clientKeyStore == null) {
Log.i(LOG_TAG, "Cert/key was not found in keystore - creating new key and certificate.");
new Thread(new Runnable() {
#Override
public void run() {
try {
// Create a new private key and certificate. This call
// creates both on the server and returns them to the
// device.
CreateKeysAndCertificateRequest createKeysAndCertificateRequest =
new CreateKeysAndCertificateRequest();
createKeysAndCertificateRequest.setSetAsActive(true);
final CreateKeysAndCertificateResult createKeysAndCertificateResult;
createKeysAndCertificateResult =
mIotAndroidClient.createKeysAndCertificate(createKeysAndCertificateRequest);
Log.i(LOG_TAG,
"Cert ID: " +
createKeysAndCertificateResult.getCertificateId() +
" created.");
// store in keystore for use in MQTT client
// saved as alias "default" so a new certificate isn't
// generated each run of this application
AWSIotKeystoreHelper.saveCertificateAndPrivateKey(certificateId,
createKeysAndCertificateResult.getCertificatePem(),
createKeysAndCertificateResult.getKeyPair().getPrivateKey(),
keystorePath, keystoreName, keystorePassword);
// load keystore from file into memory to pass on
// connection
clientKeyStore = AWSIotKeystoreHelper.getIotKeystore(certificateId,
keystorePath, keystoreName, keystorePassword);
// Attach a policy to the newly created certificate.
// This flow assumes the policy was already created in
// AWS IoT and we are now just attaching it to the
// certificate.
AttachPrincipalPolicyRequest policyAttachRequest =
new AttachPrincipalPolicyRequest();
policyAttachRequest.setPolicyName(AWS_IOT_POLICY_NAME);
policyAttachRequest.setPrincipal(createKeysAndCertificateResult
.getCertificateArn());
mIotAndroidClient.attachPrincipalPolicy(policyAttachRequest);
runOnUiThread(new Runnable() {
#Override
public void run() {
btnConnect.setEnabled(true);
}
});
} catch (Exception e) {
Log.e(LOG_TAG,
"Exception occurred when generating new private key and certificate.",
e);
}
}
}).start();
}
}
View.OnClickListener connectClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(LOG_TAG, "clientId = " + clientId);
try {
mqttManager.connect(clientKeyStore, new AWSIotMqttClientStatusCallback() {
#Override
public void onStatusChanged(final AWSIotMqttClientStatus status,
final Throwable throwable) {
Log.d(LOG_TAG, "Status = " + String.valueOf(status));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (status == AWSIotMqttClientStatus.Connecting) {
tvStatus.setText("Connecting...");
} else if (status == AWSIotMqttClientStatus.Connected) {
tvStatus.setText("Connected");
} else if (status == AWSIotMqttClientStatus.Reconnecting) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Reconnecting");
} else if (status == AWSIotMqttClientStatus.ConnectionLost) {
if (throwable != null) {
Log.e(LOG_TAG, "Connection error.", throwable);
}
tvStatus.setText("Disconnected");
} else {
tvStatus.setText("Disconnected");
}
}
});
}
});
} catch (final Exception e) {
Log.e(LOG_TAG, "Connection error.", e);
tvStatus.setText("Error! " + e.getMessage());
}
}
};
Certificate from keystore is not reading and giving me IOexception.
The error you are getting:
com.amazonaws.AmazonServiceException: User: arn:aws:sts::964546574005:assumed-role/Cognito_GTekPool3Unauth_Role/CognitoIdentityCredentials is not authorized to perform:
indicates that you have missing permission for the specified role. You will have to attach a valid policy which allows you to call the createKeysAndCertificate API on the service.
Thanks,
Rohan
Related
I have used below code to connect with hub.
Its working proper. but sometime suddenly the negotiate GET method calls thousands of time.
private HubConnection createLocalHubConnection() {
if (Common.isInternetAvailable(CallObserverTestService.this)) {
Log.i(TAG, "Create Connection");
final HubConnection loConnection = new HubConnection(WebService.getHubURL(CallObserverTestService.this));
Log.i(TAG, "Connection State1: " + loConnection.getState());
if (loConnection.getState() == ConnectionState.Disconnected) {
moProxy = loConnection.createHubProxy(CallObserverTestService.this.getString(R.string.hub));
try {
loConnection.stop();
loConnection.start().done(new Action<Void>() {
#Override
public void run(Void obj) throws Exception {
Log.i(TAG, "Connection URL: " + loConnection.getUrl());
Log.i(TAG, "SignalR ConnectionId: " + loConnection.getConnectionId());
}
}).onError(new ErrorCallback() {
#Override
public void onError(Throwable error) {
Log.i(TAG, "SignalR: onError : " + error.getMessage());
error.printStackTrace();
Log.logException(TAG, error);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.logException(TAG, e);
}
}
return loConnection;
}
return null;
}
The error is as below while calling in loop
Negotiation error: There was a problem in the negotiation with the
server
negotiate: https://MyDomain/signalr/negotiate?clientProtocol=1.3&connectionData=%5B%7B%22name%22%3A%22MyHubName%22%7D%5D
Reference link: https://github.com/SignalR/java-client/tree/master/signalr-client-sdk
I use Quickblox for chat room
My code:
final QBChatDialog dialog = DialogUtils.buildPrivateDialog(id);
dialog.setType(QBDialogType.PRIVATE);
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle params) {
try {
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setBody("Hi there!");
dialog.sendMessage(chatMessage);
} catch (SmackException.NotConnectedException e) {
Log.i("errorCheck", "Chat: NO : " + e.getMessage());
}
}
#Override
public void onError(QBResponseException responseException) {
Log.i("errorCheck", "Chat: FAIL" + responseException.getMessage());
}
});
I get this error :
Client is not, or no longer, connected. error
But I'm sure my client is connected
You need to do the following before sending message:
qbChatDialog.initForChat(QBChatService.getInstance());
I have developed an iPhone application with socket.io, it is working fine with HTTP and HTTPS.
I have developed Android application with socket.io. I was using HTTP it was working fine. Now I am trying to use HTTPS. I made some changes, but it is not at all connecting with server. Always I am getting websocket error.
I downloaded the library from https://github.com/socketio/ for iPhone and Android
Below is my sample code
try {
HostnameVerifier verifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
// Not doing any validation for testing
Log.i(TAG, "Verifying host name ::: " + hostname);
return true;
}
};
IO.setDefaultSSLContext(SSLContext.getDefault());
IO.setDefaultHostnameVerifier(verifier);
IO.Options opts = new IO.Options();
opts.reconnection = false;
opts.secure = true;
opts.transports = new String [] {WebSocket.NAME};
socket = IO.socket("https://website.com:6001", opts);
Log.i(TAG, "Initialized socket io");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "We are connected to server");
}
});
socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "We are disconnected from server");
socket.off();
}
});
socket.on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "Connection Error");
for (Object obj : args) {
Log.e(TAG, "Errors :: " + obj);
}
}
});
socket.on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "Connection Timeout Error");
}
});
socket.on("res", new Emitter.Listener() {
#Override
public void call(Object... args) {
Log.i(TAG, "got response from server");
}
});
socket.connect();
} catch (Exception e) {
Log.e(TAG, "Error :: " + e);
}
Any idea ?
I am implementing Keycloak for user and api authentication and successfully authenticate with Keyclaok server but getting error while calling API .
I am using aerogear pipe library and sample project to call server API.
https://github.com/aerogear/aerogear-android-pipe
try{
AuthzModule authzModule = AuthorizationManager.config("keycloak", OAuth2AuthorizationConfiguration.class)
.setBaseURL(new URL("URL:8080/auth"))
.setAuthzEndpoint("/realms/appname/tokens/login")
.setAccessTokenEndpoint("/realms/appname/tokens/access/codes")
.setAccountId("keycloak-token")
.setClientId("app_id")
.setClientSecret("1b9a1376-bc6e-41d2-b3e5-cee754305a1f")
.setRedirectURL("Callback")
.setScopes(Arrays.asList("user"))
.addAdditionalAuthorizationParam((Pair.create("access_type", "confidential")))
.asModule();
authzModule.requestAccess(this, new Callback<String>() {
#Override
public void onSuccess(String o) {
System.out.println("Server Response" + o);
retrieveFiles(authzModule);
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
PipeManager.config("GetFile", RestfulPipeConfiguration.class)
.withUrl(new URL("Server_URL"))
.module(authzModule)
.forClass(String.class);
Pipe<Object> documentsPipe = PipeManager.getPipe("GetFile", this);
documentsPipe.read(new Callback<List<Object>>() {
#Override
public void onSuccess(final List<Object> fileses) {
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
Please suggest possible way to resolved this issue.
try{
AuthzModule authzModule = AuthorizationManager.config("keycloak", OAuth2AuthorizationConfiguration.class)
.setBaseURL(new URL("URL:8080/auth"))
.setAuthzEndpoint("/realms/appname/tokens/login")
.setAccessTokenEndpoint("/realms/appname/tokens/access/codes")
.setAccountId("keycloak-token")
.setClientId("app_id")
.setClientSecret("1b9a1376-bc6e-41d2-b3e5-cee754305a1f")
.setRedirectURL("Callback")
.setScopes(Arrays.asList("user"))
.addAdditionalAuthorizationParam((Pair.create("access_type", "confidential")))
.asModule();
authzModule.requestAccess(this, new Callback<String>() {
#Override
public void onSuccess(String o) {
System.out.println("Server Response" + o);
retrieveFiles(authzModule);
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}catch (Exception ex){
Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
}
Than call simple http request with auth token in header.when server sending json response.
Headers:Bearer +" auth token",
Content-Type : application/json,
Accept : application/json
I'm developing a simple WebSocket in Android using AndroidAsync library:
http://www.koushikdutta.com/AndroidAsync
My Client code:
private void conectar() {
//String uri = "ws://192.167.101.142:1234";
String uri = "http://192.167.101.166:1234";
AsyncHttpClient asyncHttpClient = AsyncHttpClient.getDefaultInstance();
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(uri, "https", new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), null, new AsyncHttpClient.WebSocketConnectCallback() {
//asyncHttpClient.websocket(new AsyncHttpGet(uri), "SSL", new AsyncHttpClient.WebSocketConnectCallback() {
asyncHttpClient.websocket(uri, null, new AsyncHttpClient.WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
Log.e(TAG, "webSocket is null");
Log.e(TAG, "Metodo onCompleted");
if (ex != null) {
Log.e(TAG, ex.getMessage(), ex);
return;
}
//Log.e(TAG, "webSocket.isOpen(): " + webSocket.isOpen());
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new WebSocket.StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
Log.e(TAG, "I got a string: " + s);
//showToast("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
#Override
public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
Log.e(TAG, "I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
}
My Server code:
private void conectar() {
AsyncHttpServer server = new AsyncHttpServer();
server.listen(PORTA);
server.get("/", new HttpServerRequestCallback() {
#Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.websocket("/", new AsyncHttpServer.WebSocketRequestCallback() {
#Override
public void onConnected(final WebSocket webSocket, AsyncHttpServerRequest request) {
Log.e(TAG, "Metodo: onConnected");
_sockets.add(webSocket);
//Use this to clean up any references to your websocket
webSocket.setClosedCallback(new CompletedCallback() {
#Override
public void onCompleted(Exception ex) {
Log.e(TAG, "Metodo onCompleted from webSocket object");
try {
if (ex != null)
Log.e("WebSocket", "Error");
} finally {
_sockets.remove(webSocket);
}
}
});
webSocket.setStringCallback(new WebSocket.StringCallback() {
#Override
public void onStringAvailable(String s) {
Log.e(TAG, "Metodo onStringAvailable from webSocket object");
if ("Hello Server".equals(s))
webSocket.send("Welcome Client!");
}
});
}
});
Anyone knows tell me why Can't I connect my server?
I have tested the server code in another app websocket tester from google play.
The app server it's Ok.
However I cannot connect from my client app?