i was create twitter API key, secret key, access token, access token secret key... then i was tried to post simple text on twitter wall by using java... i was used twitter4j API for this... But its not working properly.. i got this error when i run my program.. "** 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.**"....and my code is..
static String consumerKeyStr = "";
static String consumerSecretStr = "";
static String accessTokenStr = "";
static String accessTokenSecretStr = "";
public String postSomething() throws Exception
{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKeyStr, consumerSecretStr);
AccessToken accessToken = new AccessToken(accessTokenStr,
accessTokenSecretStr);
twitter.setOAuthAccessToken(accessToken);
twitter.updateStatus("Post using Twitter4J Again");
System.out.println("Successfully updated the status in Twitter.");
return "success";
}
Related
My code looks like:
ApiClient client = new ApiClient(DEMO_REST_BASEPATH);
String clientId = "65f9b5d9-XXXX-4de6-ab3c-XXXX";
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
byte[] key = Files.readAllBytes(Paths.get("/tmp/privateKey"));
OAuth.OAuthToken token = client.requestJWTApplicationToken(clientId, scopes, key, 3600);
System.err.println(token.getAccessToken());
OAuth.UserInfo userInfo = client.getUserInfo(token.getAccessToken());
System.out.println("UserInfo: " + userInfo);
I see I get an auth token back, however I get an error message when trying to get UserInfo:
Exception in thread "main" com.docusign.esign.client.ApiException: Error while requesting server, received a non successful HTTP code 401 with response Body: '{"error":"internal_server_error","reference_id":"22e7cf18-74b4-48aa-b916-81bde96071ae"}'
at com.docusign.esign.client.ApiClient.getUserInfo(ApiClient.java:760)
Any ideas?
You are missing this line: (example on GitHub)
client.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
Your code should be something like this:
ApiClient client = new ApiClient(DEMO_REST_BASEPATH);
String clientId = "65f9b5d9-XXXX-4de6-ab3c-XXXX";
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
byte[] key = Files.readAllBytes(Paths.get("/tmp/privateKey"));
OAuth.OAuthToken token = client.requestJWTApplicationToken(clientId, scopes, key, 3600);
System.err.println(token.getAccessToken());
client.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
OAuth.UserInfo userInfo = client.getUserInfo(token.getAccessToken());
System.out.println("UserInfo: " + userInfo);
I have applications registered in Azure AD Tenant and these applications have clientid and secret.
I have a requirement to get the azure application credentials expiry date. I am using azure sdk for java in my application.
How can we get the client secret expiry date using java ?
I have googled for it but didn't find any useful links. Can anyone help me on this.
If you want to get secret expiry date in your Java application, you can call the Microsoft Graph API to get the application. Then the application's property passwordCredentials has the information. For example
Register a new application using the Azure portal
Sign in to the Azure portal using either a work or school account or
a personal Microsoft account.
If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the Azure AD tenant that you want.
In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations > New registration.
Configure Microsoft Graph permissions you need for your application
Code
//install ADAL4J get accesss token
String clientId = "your application id";
String appKey = "your client secret";
String tenantId = "your tenant id";
String authority =String.format("https://login.microsoftonline.com/",getTenantContextId())
String resourceUrl = "https://graph.microsoft.com"
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = ew AuthenticationContext(authority, false, service);
ClientCredential clientCred = new ClientCredential(
clientId, appKey);
Future<AuthenticationResult> future = context.acquireToken(resourceUrl, clientCred, null);
AuthenticationResult result = future.get();
//Call Microsoft graph api
String stringUrl ="https://graph.microsoft.com/beta/applications?$filter=appId eq '{ApplicationId}'";
URL url = new URL(stringUrl.replaceAll(" ","%20"));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + result.getAccessToken());
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
int httpResponseCode = conn.getResponseCode();
if (httpResponseCode == 200 ) {
BufferedReader in = null;
StringBuilder response;
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject jb = new JSONObject(response.toString());
For more details, please refer to the document
Update
Please use the following code to get access token
String authority = "https://login.microsoftonline.com/" + tenant;
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authority, true, service);
ClientCredential cred = new ClientCredential(clientId, clientSecret);
String resourceId ="https://graph.microsoft.com";
Future<AuthenticationResult> future = context.acquireToken(resourceId, cred, null);
AuthenticationResult result = future.get();
String accesstoken = result.getAccessToken();
Add an auth file(optional but suggested, you can directly use client id and secret in your code)
Use Azure Management Libraries for Java
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure</artifactId>
<version>1.24.2</version>
</dependency>
Code sample
public static void main(String[] args) throws IOException {
File credFile = new File(ClassLoader.getSystemResource("./others/xh.auth").getPath());
ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(credFile);
Azure.Authenticated authenticated = Azure.configure().authenticate(credentials);
String appObjectId = "b48bc188-ff55-4655-a1d0-b8590c179a99";
ActiveDirectoryApplication application = authenticated.activeDirectoryApplications().getById(appObjectId);
Map<String, PasswordCredential> map = application.passwordCredentials();
for ( Map.Entry<String,PasswordCredential> entry: map.entrySet()) {
String key = entry.getKey();
PasswordCredential value = entry.getValue();
System.out.println("Name -> " + key + " ; End date -> " + value.endDate().toString());
}
}
Output
Name -> t o m ; End date -> 2299-12-30T16:00:00.000Z
Name-> 3ba9bb7b-5251-4bbb-a373-658e346eb44d ; End date -> 2299-12-30T16:00:00.000Z
Name-> p o s t m a n ; End date -> 2299-12-30T16:00:00.000Z
Update:
You can get the application object id from portal:
Update2:
There is a getByName method:
ActiveDirectoryApplication byName = authenticated.activeDirectoryApplications().getByName("");
But there is a known problem. As the applications registered in Azure AD could have the same name. This method will not get a correct
ActiveDirectoryApplication instance as you expected. You will always get the first one in the list. (Actually, with REST API and filter, you will get a list too)
But, if you have created all the applications with different names, then you can use the getByName method.
I am trying to load a url with headers and trying to get my accessToken
Here is the code
String oauthToken = urls[0];
String tokenVerifier = urls[1];
String responseBody = null;
try {
String url = "https://api.copy.com/oauth/access?oauth_verifier=" + tokenVerifier;
String uniqueID = UUID.randomUUID().toString();
String authorization = "OAuth oauth_version=\"1.0\", oauth_signature_method=\"PLAINTEXT\", oauth_consumer_key=\""+ Constants.COPY_CONSUMER_KEY
+"\", oauth_signature=\""+ Constants.COPY_SECRET +"&" + tokenVerifier "\", oauth_nonce=\""+ uniqueID
+"\", oauth_timestamp=\""+String.valueOf(Calendar.getInstance().getTimeInMillis())+"\" , oauth_token=\""+ oauthToken +"\"";
The response gives me error
oauth_problem=signature_invalid&debug_sbs=GET&https%3A%2F%2Fapi.copy.com%2Foauth%2Faccess&oauth_consumer_key%3DCtu6CtdN1PWRo5DstoxgaaIQWZkeeWNg%26oauth_nonce%3D10525625%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1425400347545%26oauth_token%3D6aNkypb7wZoI7dbJiSrtItOTGmpaG0RL%26oauth_verifier%3D496cb46091352c4788603dcfb6e0cfb5%26oauth_version%3D1.0oauth_error_code=2000
What is wrong with my signature, same method is working for ios
You are sending the ouath_token that you have just received when you have to calculate a new Token using that received token and the request_token_secret. This new token is what you need to send as oauth_token parameter in your request.
Check my python code here.
I'm having issues invoking twitter REST API using Google OAuth Java Client. I'm able to do the first steps correctly:
Set the authorization URL,
Get the temporary token,
Generate the final token.
Then the OAuth Javadoc says:
Use the stored access token to authorize HTTP requests to protected
resources by setting the OAuthParameters.token and using
OAuthParameters as the HttpRequestInitializer.
It's in this step that I have issues. First of all if I only set the OAuthParameters.token value I'll get a null exception because the signer isn't set so what I presently have is:
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret=TWITTER_CONSUMER_SECRET;
String oauthToken = req.getParameter("oauth_token");
String oauthVerifier = req.getParameter("oauth_verifier");
OAuthGetAccessToken accessTokenRequest = new OAuthGetAccessToken(TWITTER_ACESS_TOKEN_URL);
accessTokenRequest.consumerKey=TWITTER_CONSUMER_KEY;
accessTokenRequest.signer=signer;
accessTokenRequest.transport=HTTP_TRANSPORT;
accessTokenRequest.temporaryToken=oauthToken;
accessTokenRequest.verifier=oauthVerifier;
OAuthCredentialsResponse credentials = accessTokenRequest.execute();
String token = credentials.token;
OAuthParameters params = new OAuthParameters();
params.token=token;
params.version="1.0";
params.consumerKey=TWITTER_CONSUMER_KEY;
params.signer=signer;
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(params);
HttpResponse twResponse = requestFactory.buildGetRequest(new GenericUrl("https://api.twitter.com/1.1/account/verify_credentials.json")).execute();
The result is always:
WARNING: Authentication error: Unable to respond to any of these
challenges: {} com.google.api.client.http.HttpResponseException: 401
OK {"errors":[{"message":"Could not authenticate you","code":32}]}
If I try the Authorization header given by Twitter OAuth tool through a REST Chrome extension tool it works perfectly so it's not an account issue. When I change it for the Authorization header value computed by the Google OAuth Java client library it doesn't work.
I don't get what I'm doing wrong.
Solution: Follow the tutorial in the link provided by #Arkanon, I missed refreshing the signer token secrete through:
signer.tokenSharedSecret
I just modified the code on this page about using google-oauth-java-client to send a request to Twitter and it worked fine once I replaced the relevant block with this:
while (currentLine.equalsIgnoreCase("n")) {
System.out.println("Enter the verification PIN provided by Twitter:");
currentLine = in.readLine();
}
and then added the following to the accessToken object:
accessToken.verifier = currentLine;
Once the PIN provided by the Twitter site is typed into the Java console and you hit Enter, the process completes and the protected resource can be accessed and the desired JSON response is received.
The only other changes I made to that code were to provide the Twitter constants as follows:
private static final String CONSUMER_KEY =
"enter-your-consumer-key-here";
private static final String CONSUMER_SECRET =
"enter-your-consumer-secret-here";
private static final String PROTECTED_SERVICE_URL =
"https://api.twitter.com/1.1/statuses/home_timeline.json";
private static final String REQUEST_TOKEN_URL =
"https://api.twitter.com/oauth/request_token";
private static final String AUTHORIZE_URL =
"https://api.twitter.com/oauth/authenticate";
private static final String ACCESS_TOKEN_URL =
"https://api.twitter.com/oauth/access_token";
Maybe this is not the exact same process you're hoping to achieve, but hopefully the code on that page will help you to spot anything you might have misunderstood. (And I agree that the documentation for the Google libraries is not all it could be.)
I'm using Signpost as OAuth implementation for posting to Twitter. And implemented the GoogleAppEngineOAuthConsumer and GoogleAppEngineOAuthProvider classes, but since they're pretty trivial, so I'm not providing their sources here (yet).
Here's my authentication part, which seems to work just fine.
LoginServlet.java:
// fetching the request token
OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
OAuthProvider provider = new GoogleAppEngineOAuthProvider(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, AUTHORIZATION_URL);
String redirectUrl = provider.retrieveRequestToken(consumer, CALLBACK_URL);
// cache the request token and request token secret
response.sendRedirect(redirectUrl);
CallbackServlet.java
// fetching the access token
String verifier = (String) req.getParameter("oauth_verifier");
// retrieve request token and request token secret from cache
OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
OAuthProvider provider = new GoogleAppEngineOAuthProvider(REQUEST_TOKEN_URL,
consumer.setTokenWithSecret(token, tokenSecret);
provider.setOAuth10a(true);
provider.retrieveAccessToken(consumer, verifier);
// store access token and access token secret
And here's the actual problematic part.
TweetServlet.java
OAuthConsumer consumer = new GoogleAppEngineOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
// retrieve access token and access token secret from storage
consumer.setTokenWithSecret(accessToken, accessTokenSecret);
final HTTPRequest updateStatus = new HTTPRequest(new URL("http://api.twitter.com/1/statuses/update.json"), HTTPMethod.POST);
updateStatus.setPayload(("status=" + URLEncoder.encode(message, "UTF-8")).getBytes());
consumer.sign(updateStatus);
logger.debug(new String(URLFetchServiceFactory.getURLFetchService().fetch(updateStatus).getContent()));
Each and every time it results: {"request":"/1/statuses/update.json","error":"Incorrect signature"}.
I was able to solve this by myself. The problem was that I wasn't setting a Content-Type header to the request, so the signing didn't sign the parameters and it resulted the invalid signature. Once I set it to application/x-www-form-urlencoded it started working.
final HTTPRequest updateStatus = new HTTPRequest(new URL("http://api.twitter.com/1/statuses/update.json"), HTTPMethod.POST);
updateStatus.addHeader(new HTTPHeader("Content-Type", "application/x-www-form-urlencoded"));