[ 
https://issues.apache.org/jira/browse/CAMEL-12899?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=16664046#comment-16664046
 ] 

ASF GitHub Bot commented on CAMEL-12899:
----------------------------------------

dhirajsb closed pull request #2578: CAMEL-12899: Added check for LinkedIn 
CAPTCHA, added accessToken and …
URL: https://github.com/apache/camel/pull/2578
 
 
   

This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:

As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):

diff --git 
a/components/camel-linkedin/camel-linkedin-api/src/main/java/org/apache/camel/component/linkedin/api/LinkedInOAuthRequestFilter.java
 
b/components/camel-linkedin/camel-linkedin-api/src/main/java/org/apache/camel/component/linkedin/api/LinkedInOAuthRequestFilter.java
index 51e701f3017..a82a26b252f 100644
--- 
a/components/camel-linkedin/camel-linkedin-api/src/main/java/org/apache/camel/component/linkedin/api/LinkedInOAuthRequestFilter.java
+++ 
b/components/camel-linkedin/camel-linkedin-api/src/main/java/org/apache/camel/component/linkedin/api/LinkedInOAuthRequestFilter.java
@@ -27,7 +27,6 @@
 import java.util.concurrent.TimeUnit;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.annotation.Priority;
 import javax.ws.rs.Priorities;
 import javax.ws.rs.client.ClientRequestContext;
@@ -51,6 +50,7 @@
 import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
 import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
 import com.gargoylesoftware.htmlunit.util.WebConnectionWrapper;
+
 import org.apache.http.HttpHeaders;
 import org.apache.http.HttpHost;
 import org.apache.http.HttpStatus;
@@ -158,23 +158,31 @@ private String getRefreshToken() {
                 url = String.format(AUTHORIZATION_URL_WITH_SCOPE, 
oAuthParams.getClientId(), csrfId,
                     builder.toString(), encodedRedirectUri);
             }
-            HtmlPage authPage;
+            HtmlPage authPage = null;
             try {
                 authPage = webClient.getPage(url);
             } catch (FailingHttpStatusCodeException e) {
                 // only handle errors returned with redirects
-                if (e.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
-                    final URL location = new 
URL(e.getResponse().getResponseHeaderValue(HttpHeaders.LOCATION));
-                    final String locationQuery = location.getQuery();
-                    if (locationQuery != null && 
locationQuery.contains("error=")) {
-                        throw new 
IOException(URLDecoder.decode(locationQuery).replaceAll("&", ", "));
-                    } else {
-                        // follow the redirect to login form
-                        authPage = webClient.getPage(location);
-                    }
-                } else {
-                    throw e;
-                }
+                boolean done = false;
+                do {
+                        if (e.getStatusCode() == 
HttpStatus.SC_MOVED_TEMPORARILY || e.getStatusCode() == 
HttpStatus.SC_SEE_OTHER) {
+                            final URL location = new 
URL(e.getResponse().getResponseHeaderValue(HttpHeaders.LOCATION));
+                            final String locationQuery = location.getQuery();
+                            if (locationQuery != null && 
locationQuery.contains("error=")) {
+                                throw new 
IOException(URLDecoder.decode(locationQuery).replaceAll("&", ", "));
+                            } else {
+                                // follow the redirect to login form
+                                try {
+                                    authPage = webClient.getPage(location);
+                                    done = true;
+                                } catch (FailingHttpStatusCodeException e1) {
+                                    e = e1;
+                                }
+                            }
+                        } else {
+                            throw e;
+                        }
+                } while (!done);
             }
 
             // look for <div role="alert">
@@ -184,12 +192,12 @@ private String getRefreshToken() {
             }
 
             // submit login credentials
-            final HtmlForm loginForm = 
authPage.getFormByName("oauth2SAuthorizeForm");
+            final HtmlForm loginForm = authPage.getForms().get(0);
             final HtmlTextInput login = 
loginForm.getInputByName("session_key");
             login.setText(oAuthParams.getUserName());
             final HtmlPasswordInput password = 
loginForm.getInputByName("session_password");
             password.setText(oAuthParams.getUserPassword());
-            final HtmlSubmitInput submitInput = 
loginForm.getInputByName("authorize");
+            final HtmlSubmitInput submitInput = (HtmlSubmitInput) 
loginForm.getElementsByAttribute("input", "type", "submit").get(0);
 
             // validate CSRF and get authorization code
             String redirectQuery;
@@ -212,6 +220,10 @@ private String getRefreshToken() {
             while (matcher.find()) {
                 params.put(matcher.group(1), matcher.group(2));
             }
+            // check if we got caught in a Captcha!
+            if (params.get("challengeId") != null) {
+                throw new SecurityException("Unable to login due to CAPTCHA, 
use with a valid accessToken instead!");
+            }
             final String state = params.get("state");
             if (!csrfId.equals(state)) {
                 throw new SecurityException("Invalid CSRF code!");
@@ -221,7 +233,7 @@ private String getRefreshToken() {
                 return params.get("code");
             }
 
-        } catch (IOException e) {
+        } catch (Exception e) {
             throw new IllegalArgumentException("Error authorizing application: 
" + e.getMessage(), e);
         }
     }
diff --git 
a/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/AbstractResourceIntegrationTest.java
 
b/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/AbstractResourceIntegrationTest.java
index bb38a5bc5d7..8d3a03e393e 100644
--- 
a/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/AbstractResourceIntegrationTest.java
+++ 
b/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/AbstractResourceIntegrationTest.java
@@ -20,10 +20,11 @@
 import java.util.Arrays;
 import java.util.List;
 import java.util.Properties;
-
 import javax.ws.rs.WebApplicationException;
 
 import org.apache.camel.component.linkedin.api.model.Error;
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
 import org.apache.cxf.jaxrs.client.JAXRSClientFactory;
 import org.apache.cxf.jaxrs.client.WebClient;
 import org.junit.AfterClass;
@@ -32,6 +33,9 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import static java.util.concurrent.TimeUnit.DAYS;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
 /**
  * Base class for resource tests.
  */
@@ -39,10 +43,11 @@
 
     protected static final Logger LOG = 
LoggerFactory.getLogger(PeopleResourceIntegrationTest.class);
     protected static final String DEFAULT_FIELDS = "";
+    public static final long DEFAULT_EXPIRY = MILLISECONDS.convert(60, DAYS) + 
System.currentTimeMillis();
 
     protected static LinkedInOAuthRequestFilter requestFilter;
-    private static Properties properties;
-    private static OAuthToken token;
+    protected static Properties properties;
+    protected static OAuthToken token;
     private static List<Object> resourceList = new ArrayList<>();
 
     @BeforeClass
@@ -59,6 +64,8 @@ private static LinkedInOAuthRequestFilter createOAuthHelper() 
throws IOException
         final String clientId = properties.getProperty("clientId");
         final String clientSecret = properties.getProperty("clientSecret");
         final String redirectUri = properties.getProperty("redirectUri");
+        final String accessToken = properties.getProperty("accessToken");
+        final String expiryTime = properties.getProperty("expiryTime");
 
         final OAuthScope[] scopes;
         final String scope = properties.getProperty("scope");
@@ -68,6 +75,12 @@ private static LinkedInOAuthRequestFilter 
createOAuthHelper() throws IOException
             scopes = null;
         }
 
+        // check if accessToken is set
+        if (accessToken != null) {
+            token = new OAuthToken(null, accessToken,
+                    (expiryTime != null) ? Long.parseLong(expiryTime) : 
DEFAULT_EXPIRY);
+        }
+
         final OAuthSecureStorage secureStorage = new OAuthSecureStorage() {
             @Override
             public OAuthToken getOAuthToken() {
@@ -105,6 +118,8 @@ public static void afterClass() throws Exception {
             throw new 
IllegalStateException(AbstractResourceIntegrationTest.class.getName()
                                             + ".beforeClass must be invoked 
before getResource");
         }
+        Bus bus = BusFactory.getThreadDefaultBus();
+        bus.setProperty("allow.empty.path.template.value", true);
         final T resource = 
JAXRSClientFactory.create(LinkedInOAuthRequestFilter.BASE_ADDRESS, 
resourceClass,
 //            Arrays.asList(new Object[] { requestFilter, new 
LinkedInExceptionResponseFilter() } ));
             Arrays.asList(new Object[]{requestFilter, new 
EnumQueryParamConverterProvider()}));
diff --git 
a/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/PeopleResourceIntegrationTest.java
 
b/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/PeopleResourceIntegrationTest.java
index 4caaee5f182..78e8e45fb3f 100644
--- 
a/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/PeopleResourceIntegrationTest.java
+++ 
b/components/camel-linkedin/camel-linkedin-api/src/test/java/org/apache/camel/component/linkedin/api/PeopleResourceIntegrationTest.java
@@ -104,9 +104,14 @@ public void testOAuthTokenRefresh() throws Exception {
 
         // mark OAuth token as expired
         final OAuthToken oAuthToken = requestFilter.getOAuthToken();
+        final long expiryTime = oAuthToken.getExpiryTime();
         oAuthToken.setExpiryTime(new Date().getTime());
 
-        peopleResource.getPerson("", false);
+        try {
+            peopleResource.getPerson("", false);
+        } finally {
+            token.setExpiryTime(expiryTime);
+        }
     }
 
     @Test
diff --git 
a/components/camel-linkedin/camel-linkedin-api/src/test/resources/test-options.properties
 
b/components/camel-linkedin/camel-linkedin-api/src/test/resources/test-options.properties
index 43404f5335a..23a3939e3dc 100644
--- 
a/components/camel-linkedin/camel-linkedin-api/src/test/resources/test-options.properties
+++ 
b/components/camel-linkedin/camel-linkedin-api/src/test/resources/test-options.properties
@@ -23,6 +23,10 @@ userPassword=
 clientId=
 # LinkedIn App clientSecret
 clientSecret=
+# LinkedIn access token
+accessToken=
+# LinkedIn token expiry time
+expiryTime=
 # LinkedIn App required scopes
 
scope=r_basicprofile,r_fullprofile,r_emailaddress,r_network,r_contactinfo,rw_nus,rw_company_admin,rw_groups,w_messages
 # LinkedIn App redirect URI
diff --git 
a/components/camel-linkedin/camel-linkedin-component/src/main/docs/linkedin-component.adoc
 
b/components/camel-linkedin/camel-linkedin-component/src/main/docs/linkedin-component.adoc
index 94043fa824f..c229f0a529d 100644
--- 
a/components/camel-linkedin/camel-linkedin-component/src/main/docs/linkedin-component.adoc
+++ 
b/components/camel-linkedin/camel-linkedin-component/src/main/docs/linkedin-component.adoc
@@ -89,14 +89,16 @@ with the following path and query parameters:
 |===
 
 
-==== Query Parameters (14 parameters):
+==== Query Parameters (16 parameters):
 
 
 [width="100%",cols="2,5,^1,2",options="header"]
 |===
 | Name | Description | Default | Type
+| *accessToken* (common) | LinkedIn access token to avoid username and 
password login. |  | String
 | *clientId* (common) | LinkedIn application client ID |  | String
 | *clientSecret* (common) | LinkedIn application client secret |  | String
+| *expiryTime* (common) | LinkedIn access token expiry time in milliseconds 
since Unix Epoch. | 5184000 | long
 | *httpParams* (common) | Custom HTTP params, for example proxy host and port, 
use constants from AllClientPNames |  | Map
 | *inBody* (common) | Sets the name of a parameter to be passed in the 
exchange In Body |  | String
 | *lazyAuth* (common) | Flag to enable/disable lazy OAuth, default is true. 
when enabled, OAuth token retrieval or generation is not done until the first 
REST call | true | boolean
diff --git 
a/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/DefaultOAuthSecureStorage.java
 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/DefaultOAuthSecureStorage.java
new file mode 100644
index 00000000000..a052daf9d9b
--- /dev/null
+++ 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/DefaultOAuthSecureStorage.java
@@ -0,0 +1,35 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.linkedin;
+
+import org.apache.camel.component.linkedin.api.OAuthSecureStorage;
+import org.apache.camel.component.linkedin.api.OAuthToken;
+import org.apache.camel.component.linkedin.internal.CachingOAuthSecureStorage;
+
+/**
+ * Default implementation of {@link OAuthSecureStorage}
+ * with user provided token and expiry time in msecs.
+ */
+public class DefaultOAuthSecureStorage extends CachingOAuthSecureStorage {
+
+    private OAuthToken token;
+
+    public DefaultOAuthSecureStorage(String accessToken, long expiryTime) {
+        super(null);
+        this.token = new OAuthToken(null, accessToken, expiryTime);
+    }
+}
diff --git 
a/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInComponent.java
 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInComponent.java
index 5189b2caf21..3d8f05d4cb1 100644
--- 
a/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInComponent.java
+++ 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInComponent.java
@@ -24,6 +24,7 @@
 import org.apache.camel.Endpoint;
 import org.apache.camel.component.linkedin.api.LinkedInOAuthRequestFilter;
 import org.apache.camel.component.linkedin.api.OAuthParams;
+import org.apache.camel.component.linkedin.api.OAuthSecureStorage;
 import org.apache.camel.component.linkedin.internal.CachingOAuthSecureStorage;
 import org.apache.camel.component.linkedin.internal.LinkedInApiCollection;
 import org.apache.camel.component.linkedin.internal.LinkedInApiName;
@@ -109,8 +110,12 @@ private LinkedInOAuthRequestFilter 
createRequestFilter(LinkedInConfiguration con
     }
 
     private static OAuthParams getOAuthParams(LinkedInConfiguration 
configuration) {
+        OAuthSecureStorage secureStorage = configuration.getSecureStorage();
+        if (secureStorage == null && 
!ObjectHelper.isEmpty(configuration.getAccessToken())) {
+            secureStorage = new 
DefaultOAuthSecureStorage(configuration.getAccessToken(), 
configuration.getExpiryTime());
+        }
         return new OAuthParams(configuration.getUserName(), 
configuration.getUserPassword(),
-            new CachingOAuthSecureStorage(configuration.getSecureStorage()), 
configuration.getClientId(), configuration.getClientSecret(),
+            new CachingOAuthSecureStorage(secureStorage), 
configuration.getClientId(), configuration.getClientSecret(),
             configuration.getRedirectUri(), configuration.getScopes());
     }
 
diff --git 
a/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInConfiguration.java
 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInConfiguration.java
index 26fc1b80a34..114849cdd6f 100644
--- 
a/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInConfiguration.java
+++ 
b/components/camel-linkedin/camel-linkedin-component/src/main/java/org/apache/camel/component/linkedin/LinkedInConfiguration.java
@@ -18,6 +18,7 @@
 
 import java.util.Arrays;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.camel.component.linkedin.api.OAuthScope;
 import org.apache.camel.component.linkedin.api.OAuthSecureStorage;
@@ -56,6 +57,10 @@
     @UriParam
     private OAuthSecureStorage secureStorage;
     @UriParam
+    private String accessToken;
+    @UriParam(defaultValue = "5184000")
+    private long expiryTime = TimeUnit.SECONDS.convert(60, TimeUnit.DAYS);
+    @UriParam
     private String clientId;
     @UriParam
     private String clientSecret;
@@ -116,6 +121,28 @@ public OAuthSecureStorage getSecureStorage() {
         return secureStorage;
     }
 
+    public String getAccessToken() {
+        return accessToken;
+    }
+
+    /**
+     * LinkedIn access token to avoid username and password login.
+     */
+    public void setAccessToken(String accessToken) {
+        this.accessToken = accessToken;
+    }
+
+    public long getExpiryTime() {
+        return expiryTime;
+    }
+
+    /**
+     * LinkedIn access token expiry time in milliseconds since Unix Epoch.
+     */
+    public void setExpiryTime(long expiryTime) {
+        this.expiryTime = expiryTime;
+    }
+
     /**
      * Callback interface for providing an OAuth token or to store the token 
generated by the component.
      * The callback should return null on the first call and then save the 
created token in the saveToken() callback.
diff --git 
a/components/camel-linkedin/camel-linkedin-component/src/test/resources/test-options.properties
 
b/components/camel-linkedin/camel-linkedin-component/src/test/resources/test-options.properties
index 43404f5335a..23a3939e3dc 100644
--- 
a/components/camel-linkedin/camel-linkedin-component/src/test/resources/test-options.properties
+++ 
b/components/camel-linkedin/camel-linkedin-component/src/test/resources/test-options.properties
@@ -23,6 +23,10 @@ userPassword=
 clientId=
 # LinkedIn App clientSecret
 clientSecret=
+# LinkedIn access token
+accessToken=
+# LinkedIn token expiry time
+expiryTime=
 # LinkedIn App required scopes
 
scope=r_basicprofile,r_fullprofile,r_emailaddress,r_network,r_contactinfo,rw_nus,rw_company_admin,rw_groups,w_messages
 # LinkedIn App redirect URI
diff --git 
a/platforms/spring-boot/components-starter/camel-linkedin-starter/src/main/java/org/apache/camel/component/linkedin/springboot/LinkedInComponentConfiguration.java
 
b/platforms/spring-boot/components-starter/camel-linkedin-starter/src/main/java/org/apache/camel/component/linkedin/springboot/LinkedInComponentConfiguration.java
index 44d3f44d762..b26303b7cdf 100644
--- 
a/platforms/spring-boot/components-starter/camel-linkedin-starter/src/main/java/org/apache/camel/component/linkedin/springboot/LinkedInComponentConfiguration.java
+++ 
b/platforms/spring-boot/components-starter/camel-linkedin-starter/src/main/java/org/apache/camel/component/linkedin/springboot/LinkedInComponentConfiguration.java
@@ -96,6 +96,14 @@ public void setResolvePropertyPlaceholders(
          * MUST be provided
          */
         private OAuthSecureStorage secureStorage;
+        /**
+         * LinkedIn access token to avoid username and password login.
+         */
+        private String accessToken;
+        /**
+         * LinkedIn access token expiry time in milliseconds since Unix Epoch.
+         */
+        private Long expiryTime = 5184000L;
         /**
          * LinkedIn application client ID
          */
@@ -167,6 +175,22 @@ public void setSecureStorage(OAuthSecureStorage 
secureStorage) {
             this.secureStorage = secureStorage;
         }
 
+        public String getAccessToken() {
+            return accessToken;
+        }
+
+        public void setAccessToken(String accessToken) {
+            this.accessToken = accessToken;
+        }
+
+        public Long getExpiryTime() {
+            return expiryTime;
+        }
+
+        public void setExpiryTime(Long expiryTime) {
+            this.expiryTime = expiryTime;
+        }
+
         public String getClientId() {
             return clientId;
         }


 

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


> Handle LinkedIn Captcha redirects gracefully
> --------------------------------------------
>
>                 Key: CAMEL-12899
>                 URL: https://issues.apache.org/jira/browse/CAMEL-12899
>             Project: Camel
>          Issue Type: Bug
>    Affects Versions: 2.22.1
>            Reporter: Dhiraj Bokde
>            Assignee: Dhiraj Bokde
>            Priority: Major
>              Labels: LinkedIn, camel-linkedin
>             Fix For: 2.22.2
>
>
> Currently LinkedIn component throws the exception
> {code:java}
> java.lang.SecurityException: Invalid CSRF code!{code}
> when LinkedIn responds with a CAPTCHA instead of a login token. 
> Instead it should detect ac CAPTCHA response and print an appropriate 
> message. In addition, since username and password authentication may not 
> work, the component should support configuring a user generated access token 
> to bypass the LinkedIn login process and still be able to use LinkedIn API. 



--
This message was sent by Atlassian JIRA
(v7.6.3#76005)

Reply via email to