Cloudant Unathorized request - java

I've been trying to work this problem out about accessing my cloudant DB from IBM-bluemix services.
I've set my URL in Android studio like this:
URL url = new URL("https://XXXX-XXXX-XXXX-XXXX-XXXX-bluemix.cloudant.com");
And then trying to access it by:
CloudantClient client = ClientBuilder.url(url)
.username("myusername")
.password("mypassword")
.build();
However, When i try to access/modify anything within my database,
ex:
client.createDB("test_DB");
I get the error:
Error: unauthorized. Reason: one of _admin, server_admin is required for this request.
What am i missing?
I've seen many different ways to approach querying from cloudant, but this is the closest i've gotten.
Have i just completely misunderstood how querying from an existing database works?

If you are using a Cloudant legacy API key you won't be able to perform account administrator level actions, such as listing or creating databases because the legacy API keys are associated with specific databases not the account. If that is the type of credentials you are using you can initialize the client in the way you have done and get the existing database via:
Database db = client.database("test_DB", false);

Try your credentials using curl on the command line (see https://cloud.ibm.com/docs/services/Cloudant/tutorials?topic=cloudant-databases#databases)
Verify if your account accepts legacy credentials ("username and password") or IAM tokens.
See https://cloud.ibm.com/docs/services/Cloudant/guides?topic=cloudant-ibm-cloud-identity-and-access-management-iam-#ibm-cloud-identity-and-access-management-iam-

Related

HazelCast Rest-Client Response Content -Type Configuration Problem

I have integrated the hazelcast mechanism in my project. I am able to store the the Data in the map by using the hazelcast instance reference. But I am feeling difficulty to set the response type for the rest client apis.
I am getting the response as type of Content-Type →application/binary but the required format is Content-Type:application/json
I followed the documentation provided in:HazelCast RestClient Documentation
I am storing the data by using the hazelcast instance in the below format:
Sample Format:
*Map<String, User> mymap = hazelcastinstance.getMap("testMap");
User user = new User();
mymap.put("mykey", user);*
Any one please help me with this issue
Thanks in advance
Url:
(Get Request)
http://localhost:5701/hazelcast/rest/maps/testMap/mykey
Hazelcast currently stores data in binary form or in Java object. JSON support is coming out in 3.12, which is already in BETA. You can access 3.12-BETA here: https://hazelcast.org/download/
Unfortunately, REST would not be able to return JSON in 3.12. Perhaps, something can be added in one of the later versions, possibly 4.0.

Authenticate with Cognito Federated Identities

I am having a hard time trying to figure out how to use Amazon Cognito in my web app (Java based). I want to have some kind of authentication hub (Amazon Cognito) to authenticate user with multiple Auth Providers - that's why I want to use Amazon Cognito! :)
Firstly, I set up User Pool (I have my UserPoolId: eu-central-1_xxxxxxxxxx) and created there one user. Next I created Identity Pool with IdentityPoolId (eu-central-1:yyyyyyyyyy). Then I authenticate with AWS JavaScript SDK to UserPool to get idToken and it working quite fine! I receive idToken from Cognito UserPool. Then I am sending this idToken to my backend app (Java based) and there I want to validate this idToken with IdentityPool. I added new Authentication Provider - Cognito with UserPoolId and newly created id of an App that I added in UserPool. I tried to follow with this tutorial:
https://aws.amazon.com/blogs/mobile/use-amazon-cognito-in-your-website-for-simple-aws-authentication/
But everytime I make
GetID
request I recevied Exception with
com.amazonaws.services.cognitoidentity.model.NotAuthorizedException: Token is not from a supported provider of this identity pool.
My Java code is below:
final AmazonCognitoIdentityClient identityClient = new AmazonCognitoIdentityClient(
new BasicAWSCredentials("accessKey", "secretKey"));
identityClient.setRegion(Region.getRegion(Regions.EU_CENTRAL_1));
GetIdRequest idRequest = new GetIdRequest();
idRequest.setAccountId("accountId");
idRequest.setIdentityPoolId(identityPoolId);
final String providerName = "cognito-idp.eu-central-1.amazonaws.com/eu-central-1_xxxxxxxx";
Map providerTokens = new HashMap();
providerTokens.put(providerName, idToken);
idRequest.setLogins(providerTokens);
GetIdResult idResp = identityClient.getId(idRequest);
Does anyone could help me with this task? Maybe I am doing something wrong?
Thanks,
Kamil :)
There are three pieces of data that need to match in this scenario:
Provider as configured in AWS.
Provider as put into the Logins map.
iss value (issuer) in the id token.
When I have seen this error, it has been because the value in the Logins map does not match the provider as configured in AWS.
For example, an unexpected port number or trailing slash can cause these not to match.
Beyond this, there are a couple of settings in AWS that need to line up.
Provider as configured in AWS
With a Cognito User Pool, Amazon configures this name for you, so it's non-configurable on the backend. The format of the providerName in your Java code looks good, but first I'd triple check the xxxxxxx part for a typo.
App Client settings
Then, make sure your App Client has Cognito enabled in your User Pool settings:
Federated Identities settings
Next, in your federated identities settings, verify that the user pool id and client id appear in the Cognito tab under "Authentication providers", and that they match your user pool and App Client.
JWT issuer
Finally, I would expect the error to be "Invalid login token. Issuer doesn't match providerName" if there was a problem with the iss value in the JWT. However, decoding the id token you get back and inspecting the contents (as suggested in another answer) is also good advice.
If all these pieces appear to be in place, and the error persists, please leave a comment. Happy Hacking!
When you created your user pool double check you have all the expected federated providers supported. If you use developer authenticated make sure you add that 'login....' domain as well.
Grab your/a token and look at it in jwt.io for clues as well.

specific IDs do not accept my access token in RestFB for Facebook

I try to fetch multiple objects through the RestFB API. I have a list of IDs (endpoints?) and want them to be bulk-fetched by RestFB. Therefore I use FacebookClient.fetchObjects(). The problem which now occurs is that one of the IDs in my list seems not to accept the token. I'm not that into the token system of facebook. The only token I generated is the app-token.
Two IDs used in the list:
working ID: 1104054513000418
not working ID: 1106761186063084
These IDs belong to posts which are from the same author and there is not real difference between them but the content.
Trying to fetch data by these IDs manually (no bulk-fetch) I have the same issue. So it is not an issue with the misusage of the multiple fetch method.
Code:
FacebookClient.AccessToken accessToken = new DefaultFacebookClient().obtainAppAccessToken(appId, appSecurity);
FacebookClient fbClient = new DefaultFacebookClient(accessToken.getAccessToken());
// consider filteredSocialItems as given
List<String> filteredItemIDs = filteredSocialItems.stream()
.map({ item -> item.properties.get("sourceId") })
.collect(Collectors.toList());
JsonObject json = fbClient.fetchObjects(filteredItemIDs, JsonObject.class, Parameter.with("fields", "name,id"));
Exception:
Caught: com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#100) Requires user session (code 100, subcode null)
com.restfb.exception.FacebookOAuthException: Received Facebook error response of type OAuthException: (#100) Requires user session (code 100, subcode null)
at com.restfb.DefaultFacebookClient$DefaultGraphFacebookExceptionMapper.exceptionForTypeAndMessage(DefaultFacebookClient.java:1201)
at com.restfb.DefaultFacebookClient.throwFacebookResponseStatusExceptionIfNecessary(DefaultFacebookClient.java:1122)
at com.restfb.DefaultFacebookClient.makeRequestAndProcessResponse(DefaultFacebookClient.java:1063)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:974)
at com.restfb.DefaultFacebookClient.makeRequest(DefaultFacebookClient.java:936)
at com.restfb.DefaultFacebookClient.fetchObjects(DefaultFacebookClient.java:431)
at facebookImageRefresh.run(facebookImageRefresh.groovy:48)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:48)
Solving the problem was a bit exhausting. It was an issue with an old facebook app version.
Facebook apps are created within your Facebook developer account
Since Facebook changed a lof of its API rules here lies the problem. You cannot just access a post by its ID like using 1104054513000418 you also have to prefix the ID of the page/user who created that post. So if your page's ID is 589476469431696 you actually need to create a combined ID out of both like 589476469431696_1104054513000418 -> "{page_id}_{post_id}". I have no idea if this is interchangeable.
So after creating a new app I was able to get this to work.
Another info: as I was looking for a user access token all the time - I found it within my facebook app advanced settings. But it seems I don't need it any more.

How to access Bitbucket API from a Java Desktop App via Jersey+Oltu?

As the title states it, I want to access the bitbucket API from a native Java Desktop Application. Bitbucket requires Applications to use OAuth2, and for that I found that Oltu should do the job.
However, my knowledge of OAuth is very limited and so I am stuck at a very early point. Here is what I did so far:
Step 1: I registered an OAuth Consumer with my Bitbucket Account with the following details:
Name: jerseytestapp
Description:
CallbackURL: http://localhost:8080/
URL:
Question 1: Could I automate this step?
Step 2: I ran the following Java code:
package jerseytest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
public class BitbucketJersey {
public static void main(String[] args) {
OAuthClientRequest request;
try {
request = OAuthClientRequest
.authorizationLocation("https://bitbucket.org/site/oauth2/authorize")
.setClientId("jerseytestapp")
.setRedirectURI("http://localhost:8080")
.buildQueryMessage();
System.out.println(request.getLocationUri());
} catch (OAuthSystemException e) {
e.printStackTrace();
}
}
}
Step 3: I received the following locationURI and opened in Firefox
https://bitbucket.org/site/oauth2/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A8080&client_id=jerseytestapp
Question 2: Do I need to use the browser or can I do this from the java application?
I receive the following answer message in Firefox:
Invalid client_id
This integration is misconfigured. Contact the vendor for assistance.
Question 3: What would be the correct next steps, and what is wrong with my approach?
Answer 1: You can automate the creation of OAuth Consumers, but you probably don’t want to.
Bitbucket provides documentation on how to create a consumer through their APIs, although the documentation is lacking many pertinent fields. Even so, you could still craft an HTTP request programmatically which mimics whatever Bitbucket's web interface is doing to create consumers. So yes, it could be automated.
Here's why you probably don't want to. In your case, you have three things that need to work together: your application, the end user, and Bitbucket. (Or in terms of OAuth jargon for this flow, those would be the client, resource owner, and authorization server, respectively.) The normal way of doing things is that your application is uniquely identified by the OAuth Consumer that you’ve created in your account, and all usages of Bitbucket by your application will use that single OAuth Consumer to identify your application. So unless you’re doing something like developing a Bitbucket application that generates other Bitbucket applications, you have no need to automate the creation of other OAuth Consumers.
Answer 2: You can authorize directly from your Java application.
Bitbucket states that it supports all four grant flows/types defined in RFC-6749. Your code is currently trying to use the Authorization Code Grant type. Using this grant type WILL force you to use a browser. But that’s not the only problem with this grant type for a desktop application. Without a public webserver to point at, you will have to use localhost in your callback URL, as you are already doing. That is a big security hole because malicious software could intercept traffic to your callback URL to gain access to tokens that the end user is granting to your application only. (See the comments on this stackoverflow question for more discussion on that topic.) Instead, you should be using the Resource Owner Password Credentials Grant type which will allow you to authenticate a Bitbucket’s username and password directly in your application, without the need of an external browser or a callback URL. Bitbucket provides a sample curl command on how to use that grant type here.
Answer 3: The correct next steps would be to model your code after the following sample. What is wrong with your approach is that you are trying to use a grant type that is ill-suited to your needs, and you are attempting to use your OAuth Consumer's name to identify your application instead of your Consumer's key and secret.
The following code sample successfully retrieved an access token with my own username/password/key/secret combination, whose values have been substituted out. Code was tested using JDK 1.8.0_45 and org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0.
OAuthClientRequest request = OAuthClientRequest
.tokenLocation("https://bitbucket.org/site/oauth2/access_token")
.setGrantType(GrantType.PASSWORD)
.setUsername("someUsernameEnteredByEndUser")
.setPassword("somePasswordEnteredByEndUser")
.buildBodyMessage();
String key = "yourConsumerKey";
String secret = "yourConsumerSecret";
byte[] unencodedConsumerAuth = (key + ":" + secret).getBytes(StandardCharsets.UTF_8);
byte[] encodedConsumerAuth = Base64.getEncoder().encode(unencodedConsumerAuth);
request.setHeader("Authorization", "Basic " + new String(encodedConsumerAuth, StandardCharsets.UTF_8));
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
OAuthResourceResponse response = oAuthClient.resource(request, OAuth.HttpMethod.POST, OAuthResourceResponse.class);
System.out.println("response body: " + response.getBody());
Your main problem was that you were giving the customer name instead of the client id:
.setClientId("jerseytestapp")
The only way to get the client id that I know of is to query:
https://bitbucket.org/api/1.0/users/your_account_name/consumers
However, even then it was still not working so I contacted bitbucket support. It turned out that the documentation is misleading. You actually need to use the client key instead.
.setClientId("ydrqABCD123QWER4567") // or whatever your case might be
https://bitbucket.org/site/oauth2/authorize?client_id=client_key&response_type=token

Get a google's email/username in java?

is it possible to retrieve the username of a google account that i have succesfully authenticated using OAuth?
i have retrieved the users Access tokens but i am wondering if their is a API call i can make such has https://google.api/getUserName and pass the access tokens to that call and succesfully retrieve the users email/username?
In a normal OAuth web service, all you need is the secret and id access tokens to make calls to the web service but in google you also need the username too.
Any ideas?
Take a look at http://sites.google.com/site/oauthgoog/Home/emaildisplayscope . That should work for you.
The only way I figured so far is using the Spreadsheet API.
If you request the feed, that lists all documents
https://spreadsheets.google.com/feeds/spreadsheets/private/full?alt=json
There is a field with the username as well:
response.data.feed.title.$t
Unfortunately, this means prompting the user to grant access to his GDocs account, which may be confusing..
But I don't know of any API by Google to directly get the username.
Best way, the following feed was retrieved from the Contacts Data API:
https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=0
and get next fields from the feed:
response.data.feed.id
or
response.data.feed.author.name.$t
response.data.feed.author.email.$t
http://code.google.com/intl/ja/apis/accounts/docs/AuthForInstalledApps.html#Errors
This one is PHP, i think a slight modification in JAVA could make this workout
http://www.electrictoolbox.com/google-analytics-login-php-curl-username-password/

Categories

Resources