hybrid
hybrid

Reputation: 1374

Unrecognized temporary token when attempting to complete authorization: FITBIT4J

I am trying to create a app for fitbit using fitbit4j . I found their sample code at https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java

When i tried to implement it I am getting many errors. below is their doGet function()

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
            new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
            clientConsumerKey,
            clientSecret,
            credentialsCache,
            entityCache,
            subscriptionStore
    );
    if (request.getParameter("completeAuthorization") != null) {
        String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
        String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
        APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);

        if (resourceCredentials == null) {
            throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
        }
        // Get token credentials only if necessary:
        if (!resourceCredentials.isAuthorized()) {
            // The verifier is required in the request to get token credentials:
            resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
            try {
                // Get token credentials for user:
                apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
            } catch (FitbitAPIException e) {
                throw new ServletException("Unable to finish authorization with Fitbit.", e);
            }
        }
        try {
            UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
            request.setAttribute("userInfo", userInfo);
            request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
        } catch (FitbitAPIException e) {
            throw new ServletException("Exception during getting user info", e);
        }
    } else {
        try {
            response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
        } catch (FitbitAPIException e) {
            throw new ServletException("Exception during performing authorization", e);
        }
    }
}

When i run the code it goes into the 'else' part first and i get the URL with localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in and since the 'completeAuthorization==null',

it is executing the else part again.So i manually added a value so that it will enter the 'if' section . So the new URL became localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.

Now am getting the exception 'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.

Please Help.

Upvotes: 0

Views: 254

Answers (2)

hybrid
hybrid

Reputation: 1374

public class NewServlet extends HttpServlet {

    public String apiBaseUrl = "api.fitbit.com";
    public String webBaseUrl = "https://www.fitbit.com";
    public String consumerKey = "your key";
    public String consumerSecret = "your secret";
    public String callbackUrl = "*****/run?Controller=Verifier";
    public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
    public String oauth_token = null;
    public String oauth_verifier = null;
    public String token = null;
    public String tokenSecret = null;
    public String userId = null;
    public APIResourceCredentials resourceCredentials=null;
    public FitbitApiClientAgent agent =null;
    public LocalUserDetail user=null;
    public Gson gson =null;
    public UserInfo userInfo=null;



    private static Properties getParameters(String url) {
        Properties params = new Properties();
        String query_string = url.substring(url.indexOf('?') + 1);
        String[] pairs = query_string.split("&");
        for (String pair : pairs) {
            String[] kv = pair.split("=");
            params.setProperty(kv[0], kv[1]);
        }
        return params;
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
        PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");

        //   out.println(" ----- process Request Called-----");
        String controllerValue = request.getParameter("Controller");
      // out.println(" Controller Request :  "+param);

        if (controllerValue == null) {
            //  out.println(" inside if part ");
            FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
            FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
            FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
            FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
            out.println("testing2");

            apiClientService
                    = new FitbitAPIClientService<FitbitApiClientAgent>(
                            apiClientAgent,
                            consumerKey,
                            consumerSecret,
                            credentialsCache,
                            entityCache,
                            subscriptionStore
                    );
            // out.println("<script>localStorage.setItem('api',apiClientService);</script>");   
            LocalUserDetail userDetail = new LocalUserDetail("-");

            try {
                //    out.println("testing4");
                String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
                out.println("access by web browser: " + authorizationURL);
                out.println("Your web browser shows redirected URL.");
                out.println("Input the redirected URL and push Enter key.");
                response.sendRedirect(authorizationURL);
            } catch (FitbitAPIException ex) {
                out.println("exception : " + ex);
                //Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (controllerValue.equalsIgnoreCase("Verifier")) {

            oauth_token = request.getParameter("oauth_token");
            oauth_verifier = request.getParameter("oauth_verifier");
            resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);

            if (resourceCredentials == null) {
                out.println(" resourceCredentials = null ");
                throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
            }
            if (!resourceCredentials.isAuthorized()) {
                resourceCredentials.setTempTokenVerifier(oauth_verifier);
                apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
            }
            userId = resourceCredentials.getLocalUserId();
            token = resourceCredentials.getAccessToken();
            tokenSecret = resourceCredentials.getAccessTokenSecret();
            user = new LocalUserDetail(userId);
            userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
            user = new LocalUserDetail(userId);
            agent = apiClientService.getClient(); 

            response.sendRedirect("http://localhost:8084/FitbitClientCheck/");

}

Upvotes: 0

hybrid
hybrid

Reputation: 1374

Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.

Upvotes: 1

Related Questions