how to avoid repeated authorizations from linkedin to same application - java

final LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(consumerKeyValue, consumerSecretValue);
LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken(callbackUrl);
session.setAttribute("requestToken", requestToken);
String authUrl = requestToken.getAuthorizationUrl();
return new ModelAndView("redirect:" + authUrl);
I am using the above code block to make user grant permission to my application from LinkedIN.
The authorization screen is appearing everytime when I redirect user to authURL with the same default scope.
Not able to figure out if I am missing anything here.

You should change your OAuth endpoint from https://www.linkedin.com/uas/oauth/authorize to https://www.linkedin.com/uas/oauth/authenticate. This should work for you.

Related

Problem getting the userName from jwtToken

I implemented security for my application using JWT tokens. I make a post request to the /auth endpoint (passing userName and password) and get back a token, which I then use for further requests to the other endpoints. Everything works perfectly fine, but I can't get the userName out of this token. Here' my controller method:
#GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<List<SongList>> getSongListsForUser(#RequestParam("userId") String ownerId) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String userId = auth.getName();
return ResponseEntity.ok(userId.equals(ownerId)
? songListDAO.findListsOf(userId)
: songListDAO.findPublicListsOf(ownerId));
}
Found this solution here on stackoverflow.
I put a breakpoint at the line of the return statement to inspect whats inside the userId and got this:
Why this is not working? What do I have to do to get the userName (=userId) from the jwt token?

Error while requesting an access token. No accessTokenResponse object recieved, maybe a non HTTP 200 received?

I was following this tutorial: https://developers.docusign.com/esign-rest-api/code-examples/config-and-auth
(I used java)
In the third step I dont know how to get the code that is sent back form DocuSign as query param in the redirect uri:
// Java request auth token
**String code = "{ENTER_AUTH_CODE_FROM_PREVIOUS_STEP}";**
// assign it to the token endpoint
apiClient.getTokenEndPoint().setCode(code);
// optionally register to get notified when a new token arrives
apiClient.registerAccessTokenListener(new AccessTokenListener() {
#Override
public void notify(BasicOAuthToken token) {
System.out.println("Got a fresh token: " + token.getAccessToken());
}
});
// following call exchanges the authorization code for an access code and updates
// the `Authorization: bearer <token>` header on the api client
apiClient.updateAccessToken();
I get an error saying the requested access token is null. Below is the error:
Error while requesting an access token. No accessTokenResponse object received, maybe a non HTTP 200 received?
Has anybody ever got the same one or could maybe someone tell me how to fix it.
I ran below code and its working fine for me, after getting code from the previous step in the URL:
public static void main(String[] args) {
String IntegratorKey = "[Your_Integrator_Key]";
String ClientSecret = "[Your_Secret_Key]";
String RedirectURI = "https://www.getpostman.com/oauth2/callback";//This REDIRECT_URI should match whats configured with IntegratorKey in your Sandbox account
String AuthServerUrl = "https://account-d.docusign.com";
String RestApiUrl = "https://demo.docusign.net/restapi";
ApiClient apiClient = new ApiClient(AuthServerUrl, "docusignAccessCode", IntegratorKey, ClientSecret);
apiClient.setBasePath(RestApiUrl);
apiClient.configureAuthorizationFlow(IntegratorKey, ClientSecret, RedirectURI);
Configuration.setDefaultApiClient(apiClient);
String code = "{ENTER_AUTH_CODE_FROM_PREVIOUS_STEP}";
apiClient.getTokenEndPoint().setCode(code);
apiClient.registerAccessTokenListener(new AccessTokenListener() {
#Override
public void notify(BasicOAuthToken token) {
System.out.println("Got a fresh token: " + token.getAccessToken());
}
});
apiClient.updateAccessToken();
}
To get the code returned by DocuSign from browser, you need to have a WEBApp to which DocuSign will redirect the browser, this same callback URL should be configured in your DS Sandbox's REDIRECT_URI, for instance if you WEBApp callback URL is http://locahost:8080/docusignapp/callback, then this should be added in REDIRECT_URI in IntegratorKey and same needs to be added when calling DS URL to authenticate a user. Once DS authenticates the user, it will redirect the browser to your APP url. On hitting your WEBApp then you need to read the URL and strip off the code part using Javascript, then run the step2 to get the access Token. A sample JS code to strip the code part is:
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
var authCode = vars["code"];
In the example which you share they did it using Standalone code, where you are manually copying the code part from the URL after authentication and running the step2.

The access_token invalid

I get an issue from oltu(version 0.31). I can get code and access_token successfully. But, if I access protect resource, the error said: invalid access token. when I print resourceResponse.getBody() still said invalid access token. If change to httpclient or httpURLConnection all is fine. Would you please tell me what am I wrong in my code
public String getUserInfo(String accessToken) throws OAuthSystemException, OAuthProblemException {
System.out.println("Get User info access Token: " + accessToken);
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
System.out.println("111111111111111111111");
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(OauthConfig.userInfo).setAccessToken(accessToken).buildQueryMessage();
System.out.println("22222222222222222222222");
OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET, OAuthResourceResponse.class);
System.out.println("3333333333333333333333333");
System.out.println(resourceResponse.getBody());
return resourceResponse.getBody();
}
Closed this question. I found issue. my server access Token name is "accessToken", but oltu default name is "access_token". So, need to inheritance the OAuthBearerClientRequest and re-code all method.

is it available save the user session on web server?

This code is only for a user.
I'm looking for the way to make this for multiple user.
Please, give me some tips.
To run the batch job, I know that some variables (is_authorized, requestToken and accessToken) should be removed. I tried to use spring-social-tumblr(on github)but it was not easy to use ConnectionRepository. so I tried to use signpost.
After signing with signpost, how could I set the user access token for multi-user?
Is it right to use OAuthConsumer class?
#Controller
public class TumblrProfileController {
private OAuthService service;
private Token requestToken; //should be removed for multiuser
private Token accessToken; // same above
private static final String PROTECTED_RESOURCE_URL = "http://api.tumblr.com/v2/user/info";
#Autowired
private JobLauncher jobLauncher;
#Autowired
private Job job;
#Inject
private ConnectionRepository connectionRepository;
Logger log = LoggerFactory.getLogger(this.getClass());
private boolean is_authorized = false;
#RequestMapping(value = "/tumblr/webrequest", method = RequestMethod.GET)
public String home(OAuthConsumer user, Model model) {
final String PROTECTED_RESOURCE_URL = "http://api.tumblr.com/v2/user/info";
service = new ServiceBuilder().provider(TumblrApi.class).apiKey("clientKey") .apiSecret("secretKey").callback("http://localhost:8080/pen/tumblr/login").build();
log.info("Fetching the Request Token...");
// Obtain the Request Token
requestToken = service.getRequestToken();
log.info("Now go and authorize Scribe here:");
String redirectUrl = service.getAuthorizationUrl(requestToken);
log.info(redirectUrl);
return "redirect:" + redirectUrl;
}
#RequestMapping(value = "/tumblr/login", method = RequestMethod.GET)
public String login(#RequestParam(required = false) final String oauth_verifier) {
Verifier verifier = new Verifier(oauth_verifier);
// Trade the Request Token and Verfier for the Access Token
log.info("Trading the Request Token for an Access Token...");
accessToken = service.getAccessToken(requestToken, verifier);
log.info("Got the Access Token!");
log.info("(if your curious it looks like this: " + accessToken + " )");
// Now let's go and ask for a protected resource!
log.info("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
log.info("Got it! Lets see what we found...");
log.info(response.getBody());
log.info("Thats it man! Go and build something awesome with Scribe! :)");
run();
is_authorized = true;
return "tumblr/feed";
}
public void run() {
try {
if(! is_authorized ) return;
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
log.info("[2nd Call ]Got it! Lets see what we found...");
log.info(response.getBody());
} catch (Exception e) {
e.printStackTrace();
}
}
Although I've not used Spring Social Tumblr (it's a community-led project), the process shouldn't be much (or any) different than using Spring Social with Facebook or Twitter.
Note that in this code, you're doing too much work. You're going to the trouble of redirecting to Tumblr for authorization and then handling the redirect to exchange the request token and verifier for an access token. Certainly, those things must be done, but with Spring Social there's absolutely no reason why you have to do those things. That's what ConnectController is for. ConnectController handles all of that, creates and persists the connection, and (generally speaking) you never have to muck about with OAuth directly. And, it has no problem working with multiple users.
May I recommend that you look at the Spring Social Showcase example at https://github.com/spring-projects/spring-social-samples/tree/master/spring-social-showcase to see how it's done? That example connects with Facebook, Twitter, and LinkedIn, but there's really no reason why it couldn't connect to Tumblr in the same fashion. For a much simpler approach that leverages Spring Boot and automatic configuration, you might also have a look at https://github.com/spring-projects/spring-social-samples/tree/master/spring-social-showcase-boot. (Note, however, that Spring Boot doesn't have autoconfig for Tumblr, so there'd still be some manual config required.)

Facebook4j with OAUTH Access Token

Is any one help me to provide a example for OAuth access token for the facebook by getting the user credentials and and allows the fields similar to linkedin API.
I tried to use like
Configuration configuration = createConfiguration();
FacebookFactory facebookFactory = new FacebookFactory(configuration );
Facebook facebookClient = facebookFactory.getInstance();
AccessToken accessToken = null;
try{
OAuthSupport oAuthSupport = new OAuthAuthorization(configuration );
accessToken = oAuthSupport.getOAuthAppAccessToken();
}catch (FacebookException e) {
logger.error("Error while creating access token " + e.getLocalizedMessage(), e);
}
public Configuration createConfiguration() {
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(APIConfiguration.DEBUG_ENABLED);
confBuilder.setOAuthAppId(APIConfiguration.APP_ID);
confBuilder.setOAuthAppSecret(APIConfiguration.APP_SECRET);
confBuilder.setUseSSL(APIConfiguration.USE_SSL);
confBuilder.setJSONStoreEnabled(APIConfiguration.JSON_STORE_ENABLED);
Configuration configuration = confBuilder.build();
return configuration;
}
i got access token but i could search users it shows
SEVERE: Error while getting the facebook users {"error":{"message":"(#200) Must have a valid access_token to access this endpoint","type":"OAuthException","code":200}}
FacebookException [statusCode=403, response=HttpResponse{statusCode=403, responseAsString='{"error":{"message":"(#200) Must have a valid access_token to access this endpoint","type":"OAuthException","code":200}}
', is=sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#1232784a, streamConsumed=true}, errorType=OAuthException, errorMessage=(#200) Must have a valid access_token to access this endpoint, errorCode=200]
at facebook4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:189)
at facebook4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
at facebook4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:93)
at facebook4j.FacebookImpl.get(FacebookImpl.java:2095)
at facebook4j.FacebookImpl.searchUsers(FacebookImpl.java:1799)
at facebook4j.FacebookImpl.searchUsers(FacebookImpl.java:1795)
How would i get the OAUTH using call back url i tried redirect_uri with http://www.google.com but it does not give any code.
It is my java console application
Define accessToken as following example:
accessToken = new AccessToken("CAACEdEose0cBAFpfeSxd3WFzkUfm4l4PTKtLblS0hpbOFQcanzYciYMCSuFNOgiZBEtjxWZCHvwU0iP4cTe7aHXeNB5nQOC88ECE1lzVvjNKPjXNsGmJfbNfGEULQ0zEfeTla3Puknj6AGcsPy5VKKEQdJ3FbJ20RRemtgAGh05kgXsXnLrdfCPq6e6eFyu8dWxL1ZBv0EZBe9le3m0U");
where the accesToken string is obtained from https://developers.facebook.com/tools/accesstoken/
I inspired by using your code and I had similar mistake. The solution seems to be to register the application properly in the faceboook developer center = https://developers.facebook.com/ where the application must be created, edited, submitted and approved by the center.
I think you're missing this line:
facebookClient.setOAuthAccessToken( accessToken );

Categories