PayPal RestApi get UserInfo - java

Paypal login workflow is https://www.paypalobjects.com/webstatic/en_US/developer/docs/lipp/oic_flowchart.png
In web application our guys did 2 steps from previous picture and put to database authtoken and refreshToken for customers.
I want later get UserInfo (step 3)
Documentation says that we can get userInfo with GET request with Autorization using accessToken.
https://developer.paypal.com/docs/api/#get-user-information
I tried:
I get access token by App_ID and Secret_Key.
If I put it to GET request i take userInfo for owner paypal application. I cannot put customerID(user_id) to this GET request as params.
If I put customer accessToken to GET request I get unauthorized error, because customer accessToken is old.
I need to refresh it with refreshToken, but I cannot do it.
Server answer is Error code : 400 with response : {"error_description":"Unable to refresh access token","error":"invalid_request","correlation_id":"fee0c71c02cda","information_link":"https://developer.paypal.com/docs/api/#errors"}
Why I cannot refresh accesstoken? (I didn't find any answer in forum)
Or maybe I cannot get User information later and we should do it immediately after step 2?

I choose step 2, i just try valid accessToken from User. And it works.
But If you want refresh token you should send request using autorization by right client_id and client-secret.

Related

Didn't get the refresh token in response of access token call with Authorization Code Grant Request in FusionAuth

I am using FusionAuth for authentication. I have created one application in the FusionAuth. It has oAuth configured.
http://localhost:9011/oauth2/authorize?access_type=offline&prompt=consent&response_type=code&client_id=9ecc54b7-6f79-4105-a208-ca61e6157b58&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fipos%2Frest%2FfusionAuth%2FcallBack
This is my authorization url to one the FusionAuth login page.
Once I hit the link and enter the user name and password, I get the call back on configured call back url in my java jersey api.
I get the following details in the call back request.
code - dZgq5Xd0YmAQXZ2JIzkih832iojimgLUPwT7yoH9-TY
locale - en_US
userState - AuthenticatedNotRegistered
Here I am using Scribe Java library for OAuth authentication
I make call to get the access token call usnig the Scribe java libary with the given authorization code and grant_type is authorization_code.
Here this call get success and I get the below detail in the response.
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRRZTA1Uk1vN19oVjZUUnpLVUQ1aXpRU2NSOCJ9.eyJhdWQiOiI5ZWNjNTRiNy02Zjc5LTQxMDUtYTIwOC1jYTYxZTYxNTdiNTgiLCJleHAiOjE1Nzc3MTg0NjgsImlhdCI6MTU3NzcxODM0OCwiaXNzIjoiYWNtZS5jb20iLCJzdWIiOiI3ZWE3OWRhZi1hZjExLTQ1MTUtODljYS1iOGFjYTFjN2I5YTEiLCJhdXRoZW50aWNhdGlvblR5cGUiOiJQQVNTV09SRCIsImVtYWlsIjoiZGhhdmFsYmhvb3Q5M0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiZGhhdmFsYmhvb3QifQ.eA0Xi6nEZhWaTMd-P26ESdE3NsyXNRNVBKBdBvHxvzfHgXYJiN2pf-16mY8JK-4-1g3vZF7Cwv-SkP4iZAIJCYYc3uBW8Qlcjjn9cyi7_RggBBBsErcs2acRIt-D5NpnVJfkxHwGAs9fO6a2Win98GGYyv1nzBG9OhWkyZJTy4QxzlgXNrkQIzTuzRwLkRFzKCT95pqfsOYb_MXPuAksg5q1SHIj8qtbO7EO-vMbpmiok1C-Wflbiq2X_tq17QBKbO4JAMLm9_pCZse1tqLyNP4fIh3VHTz7OdbbXvug2Tpk_yTWLVL_29XC87-91R5iXeezLjADkdi1yXMUdHioOw",
"expires_in": 119,
"token_type": "Bearer",
"userId": "7ea79daf-af11-4515-89ca-b8aca1c7b9a1"
}
Here, I do not get the refresh_token, in any case, user first time login or in any case.
This is JWT token and I had reduced the expiry time to 120 seconds.
In application OAuth setup I enable Generate refresh tokens option.
The only problem here I have is, I do not receive the refresh token.
Help me with this.
Thank you.
To obtain a Refresh Token as a result of the Authorization Code Grant, you'll need to request the offline_access scope.
https://fusionauth.io/docs/v1/tech/oauth/endpoints#authorization-code-grant-request
You can modify your request as follows (line breaks added for readability)
http://localhost:9011/oauth2/authorize?
scope=offline_access
&prompt=consent
&response_type=code
&client_id=9ecc54b7-6f79-4105-a208-ca61e6157b58
&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fipos%2Frest%2FfusionAuth%2FcallBack
As a side note, adding prompt=consent is fine, but it will not affect the request as this is not yet available in FusionAuth. Please upvote the feature request if this is something you'd like to see in an upcoming release. https://github.com/FusionAuth/fusionauth-issues/issues/411

How to get an access token using a refresh token in Java?

I am currently implementing Contact Application using Google Contact API in Java. I have completed steps of authorization and obtained an access token and a refresh token.
Now I have the CLIENT_ID , CLIENT_SECRET AND REFRESH_TOKEN with me . But the access token is getting expired within an hour.
Can someone tell how to automatically generate an access token using a refresh token in Java?
You can use Google OAuth2 client library for getting a new access token using a refresh token.
Here is my code for getting a new access token:
public TokenResponse refreshAccessToken(String refreshToken) throws IOException {
TokenResponse response = new GoogleRefreshTokenRequest(
new NetHttpTransport(),
new JacksonFactory(),
refreshToken,
"your clientId",
"your clientSecret")
.execute();
System.out.println("Access token: " + response.getAccessToken());
return response;
}
For more information read the official Google API guide:
OAuth 2.0 and the Google OAuth Client Library for Java
I have implemented this scenario in two ways. Not sure they are the best or not but works well for me.
In both cases you have to store the refresh token along with the email id of the user. Then you have to make a HTTP request in the below format.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=**<your_client_id>**&
client_secret=**<your_client_secret>**&
refresh_token=**<refresh_token>**&
grant_type=refresh_token
It will return the access_token and expires_in
Source
Now the question is how and when to do the http request. So for that I have two ways.
1st one
Store the emailid,refresh token, access token and the current time+3600 seconds. In your database you can schedule to check the expire time in every 5 min and if current time of any user is going to reach(before 5 or 10 min) the expire time, get the refresh token and update the value for that particular user. And during api call just fetch the access token of the user.
2nd one
When user do login in your site, get the access token and current time+ 3600secs and store it in browser cookies. Now before doing any api call just check whether the current time(time when api call is done) is less than the expire time(stored in cookie). If its true then you can use the previous access token else get a new one and again update the cookie. Also you have to put another condition that if the cookie is not present at all then also you have to get new refresh token.

How to get user information after REST authentication on client side?

I have Spring REST backend and Angular frontend.
Authentication is performed using a POST request to "/login" URL with username and password inside request JSON body (I use form based authentication).
REST backend replies with OK code. Everything is fine and I can perform other requests from frontend that requires authentication.
But frontend need to know what is the role of authenticated user so that it can display a proper view/rote for it. And where can we get this role on a frontend? The only response we got from authentication was OK and that is fine for REST.
We can get user information by performing GET request to "/users/[user_id]". But we don't have user id, just user name.
So the question is - what is a correct way for REST to get role (or other user information) from frontend having just user name?
As a workaround I can create new request on a backend that takes user name instead of id, or I can add user id to authentication response. But I'm not really sure that is a correct way from REST perspective.
You can not override HTTP Methods.So,if you are planning to write GET call with diffrent query parameters with the same path,then it is not allowed.You need to write two GET paths.
e.g.
GET /users/userid/{id}
GET /users/username/{name}
And in the second call,you can add desired logic for getting role in the second one.
There are two way's of doing it.
1) After successful authentication from the server, do one more $http call to the server with username from which you can fetch details from a server logic that fetches and store that result in the $rootScope.This info will be available through out the app.
2) When you are authenticating the user, if the user is valid then fetch his details and store those in an object.
Now in your server logic while returning response you can do like below
response.setHeaders("User",userDetilsObj);
NOTE: response is a HttpServletResponse object.
After the request is completed as you said we will get a status OK response that is 200. To access the user details at JS side follow below code
if(response.status == '200/OK'){
$rootScope.user = response.getHeaders().User;//In this object all the user details set at server side are available now..
}
Hope this gives you some light on how to achieve your desired results.
Get the user information from server at the the time when you authenticates the user.Pass the user details on successful user authentication.
After discussing the issue with #JBNizet in comments I decided to change REST endpoint from "/users/:user_id" to "/users/:user_name".

google api androidpublisher error code 403

I am stucking with the following problem like one month already, I am trying to verify an inapp purchase by using the following api :https://developers.google.com/android-publisher/authorization
I followed every step from the documentation(doing everthing with Postman Rest Client from Chrome), I can retrieve an accesstoken and a refresh token, but whenever when I try to query a purchase it results in error code 403 access not configured, BUT I CONFFIGURED IT IN THE SETTINGS!
anybody with an idea maybe?
It is far from straightforward to get an accesstoken for this API. This blog post helped get me started in the right direction, but I've outlined my own process that does not depend on using any external scripts to work. The steps are:
Obtain a client ID and secret (one-time)
Obtain a Refresh Token (one-time)
Use the Refresh Token to obtain an Access Token (once per hour)
4 Use the access token to access the API
Each of these steps are detailed below:
Obtaining Client ID and Secret
Go to the the Google Developer's console
Go to your project page
Select "Consent Screen" on the left side and make sure that the email address and Product name fields are set
Select "Credentials" from the left menu, and select "create a new client id"
Leave Application type set to "Web application" and set "Authorized redirect URI" to https://localhost. You do not need to change the Authorized JavaScript Origins.
Click "Create Client ID" and record the Client ID and Client secret that result.
Obtaining a Refresh Token
In web browser, enter the following URL (substituting correct value for client_id):
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=https://localhost&client_id=XXXX
Accept any requests for authorization that appear
You will then be redirected to a URL like this:
https://localhost/?code=4/k0TenvwICIgmBoQOazJy4_EnJr6-.clLqtp_vVAIbEnp6UAPFm0GASPqQigI
Copy the code from the latter part of this URL
Use wget to convert this code into refresh token; substitute CODE, CLIENT_ID, and CLIENT_SECRET
wget --debug --post-data="grant_type=authorization_code&code=CODE&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=https://localhost" https://accounts.google.com/o/oauth2/token
The resulting JSON file will contain an access_token and a refresh_token. Record the refresh_token value
Obtaining an Access Token
send a POST request to https://accounts.google.com/o/oauth2/token with the following fields set (substitute REFRESH_TOKEN, CLIENT_ID, CLIENT_SECRET)
grant_type=refresh_token
refresh_token=REFRESH_TOKEN
client_id=CLIENT_ID
client_secret=CLIENT_SECRET
You will get back a JSON string containing an access_token that will be good for one hour.
Using the Access Token to make API request
Fetch from
https://www.googleapis.com/androidpublisher/v1.1/applications/PACKAGENAME/inapp/SKU/purchases/PURCHASETOKEN
with an Authorization header containing the access token, e.g:
Authorization: Bearer ya29.1.AADtN_WoM4-4Fb1voFL-emcUWluijCzwvc9Z-FYM9SPvK03HCbGkdROJTVVPSLHK2IlVJQ
You may also be able to pass the access token as an HTTP query parameter, e.g.
https://www.googleapis.com/androidpublisher/v1.1/applications/PACKAGENAME/inapp/SKU/purchases/PURCHASETOKEN?authorization_token=AUTHTOKEN
I had a similar problem as you. Answer by mmigdol is helpful, but it didn't help me. I finally managed to solve it by looking at links generated here: https://developers.google.com/oauthplayground/
Apparently, Android publisher scope
https://www.googleapis.com/auth/androidpublisher
needs to be added into the link requesting authorisation code (before even generating refresh token) by adding:
&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fandroidpublisher
to get this:
https://accounts.google.com/o/oauth2/auth?redirect_uri=<YOUR_REDIRECT_URI>&response_type=code&client_id=<YOUR_CLIENT_ID>&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fandroidpublisher&approval_prompt=force&access_type=offline

Post to Facebook Page wall using RestFB api

I am trying to post on the wall of a facebook page. I am able to post on the user wall using App Access token.
I got the App Access Token through extending the DefaultFacebookClient
public class ConnectionService extends DefaultFacebookClient{
public ConnectionService(String appId, String appSecret) {
AccessToken accessToken = this.obtainAppAccessToken(appId, appSecret);
this.accessToken = accessToken.getAccessToken();
}
}
With this I am able to post to user wall using the appID and appSecret. But when I tried to post to Page Wall
i get error of " The user hasn't authorized the application to perform this action"
Anyone can advice?
To post on a facebook page wall, you will need to follow these steps:
Head over to https://developers.facebook.com/tools/explorer
Click on "Get Access Token"
Under "Extended Permissions" tab, select select manage_pages and publish_actions and hit "Get Access Token"
Now under Graph API, under Get call, type in "me/accounts" and hit Submit
In the screen below, you will see the "data" json object with all your pages and page access tokens.
Grab the desired page token access and replace the PAGE_ACCESS_TOKEN in the code below with this token.
Replace PAGE_NAME with your page name (the page name slug in the URL).
Run the below code and that should do the job :)
final FacebookClient fb = new DefaultFacebookClient(PAGE_ACCESS_TOKEN);
final Page page = facebookClient.fetchObject(PAGE_NAME, Page.class);
facebookClient.publish("PAGE_NAME/feed", FacebookType.class, Parameter.with("message", "RestFB test"));
The App Access Token is the most basic one, and will not allow you to post anything. In order to post something to a Facebook Page (as a Page), you need to get a Page Access Token.
The process is a bit complicated, because you actually need to authorize the user with the "manage_pages" permission first, with the User Access Token you can call the API to get a Page Access Token (/me/accounts).
See those links:
https://developers.facebook.com/docs/facebook-login/
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/
Btw, the REST API is deprecated: https://developers.facebook.com/blog/post/616/
You can also try the "Client Token" (Developer Settings > Advanced), i never worked with that one but it could be the easiest solution. In any case, an App Access Token is the wrong one.
Make sure that the scopes you mentioned while authenticating user includes manage_pages also. This error occurs when you have not included this in your scope. Refer this
Since u r generating access token from java class. u can set the permissions u require from user in ur manage app link from ur facebook profile page and get the access token here.....

Categories

Resources