cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
If you’ve changed your email address, now's the perfect time to update it on your Dropbox account and we’re here to help! Learn more here.

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Re: No CSRF Token loaded from session store.

No CSRF Token loaded from session store.

joelaugusto97
Explorer | Level 3

I'm trying to integrate a spring boot application with Dropbox, the application is working perfectly locally however I have this error "No CSRF Token loaded from session store." in production. I'm using SDK 4.0.0.

Note: The application works a few times in production but the error continues most of the time

3 Replies 3

Greg-DB
Dropbox Staff

Based on the context and version number you supplied, it sounds like the you're using the official Dropbox API v2 Java SDK. Can you also share the relevant code snippet(s) (but don't include any access/refresh token(s)), as well as the steps you're following when this issue occurs? Thanks in advance!

joelaugusto97
Explorer | Level 3

 

import lombok.RequiredArgsConstructor;
import mz.co.instite.certifications.organization.domain.Organization;
import mz.co.instite.certifications.organization.infrastructure.persistence.OrganizationRepository;
import mz.co.instite.certifications.user.domain.User;
import mz.co.instite.certifications.user.domain.UserRole;
import mz.co.instite.certifications.user.infrastructure.UserRepository;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Controller
@RequestMapping(path = "/api/v1/oauth/dbx")
@RequiredArgsConstructor
@CrossOrigin
public class DbxOauthController {
    private final DbxFileSystem dbxFileSystem;
    private final UserRepository userRepository;
    private final OrganizationRepository organizationRepository;
    private User user;

    @GetMapping("/start")
    public ResponseEntity<?> authStart(HttpServletRequest request) {

            Map<?, ?> authResponse = dbxFileSystem.authorize(request);
            String authorizeUrl = (String) authResponse.get("authorizeUrl");

            if (Objects.nonNull(authorizeUrl)) {
                //response.sendRedirect(authorizeUrl);
                return ResponseEntity.ok(authorizeUrl);
            }
            return ResponseEntity.badRequest().body("Falha ao autorizar o pedido.");


    }

    @GetMapping("/finish")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> authFinish(HttpServletRequest request) {
        try {
            Map<String, Object> token = dbxFileSystem.getTokenFromUri(request);
            setAccessToken((String)token.get("accessToken"),(String)token.get("refreshToken"));
            return ResponseEntity.ok(token);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(exceptionToResponse(e.getMessage()));
        }
    }
}
import com.dropbox.core.*;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.DbxPathV2;
import com.dropbox.core.v2.files.*;
import mz.co.instite.certifications.infrastructure.fileSystem.FileResponse;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

public class DbxFileSystem {
    @Autowired
    HttpServletRequest request;

    private final DbxRequestConfig requestConfig;
    private final String redirectUri;
    private DbxPKCEWebAuth pkceWebAuth;
    private final String sessionKey = "dbx-auth-csrf-token";
    private final String storagePath;
    private DbxAppInfo appInfo;
    private String accessToken;

    public DbxFileSystem(String appKey, String redirectUri, String storagePath) {
        this.requestConfig = DbxRequestConfig.newBuilder("insite-certifications").build();
        this.redirectUri = redirectUri;
        this.appInfo = new DbxAppInfo(appKey);
        this.pkceWebAuth = new DbxPKCEWebAuth(requestConfig, appInfo);
        this.storagePath = storagePath.startsWith("/") ? storagePath : "/" + storagePath;
        this.accessToken = "";
    }

    /**
     * Authorizes a user using OAuth2 PKCE
     *
     * @param appKey
     * @return
     */
    public Map<String, ?> authorize(String appKey) {
        this.appInfo = new DbxAppInfo(appKey);
        return authorize();
    }

    public Map<String, ?> authorize() {
        DbxSessionStore sessionStore = new DbxStandardSessionStore(request.getSession(), sessionKey);
        DbxWebAuth.Request authRequest = DbxWebAuth.newRequestBuilder()
                .withRedirectUri(redirectUri, sessionStore)
                .withScope(Arrays.asList("files.content.read","files.content.write"))
                //.withTokenAccessType(TokenAccessType.ONLINE)
                .build();

        Map<String, String> response = new HashMap<>();
        try {
            response.put("authorizeUrl", pkceWebAuth.authorize(authRequest));
        }catch (java.lang.IllegalStateException e){
            pkceWebAuth = new DbxPKCEWebAuth(requestConfig, appInfo);
            response.put("authorizeUrl", pkceWebAuth.authorize(authRequest));
        };

        return response;
    }

    public Map<String, ?> authorize(HttpServletRequest request) {
        this.request = request;
        return authorize();
    }

    public Map<String, Object> getTokenFromUri(HttpServletRequest request) throws DbxException, DbxWebAuth.NotApprovedException, DbxWebAuth.BadRequestException, DbxWebAuth.BadStateException, DbxWebAuth.CsrfException, DbxWebAuth.ProviderException {
        DbxAuthFinish response = pkceWebAuth.finishFromRedirect(redirectUri, new DbxStandardSessionStore(request.getSession(), sessionKey), request.getParameterMap());
        Map<String, Object> tokens = new HashMap<>();
        tokens.put("accessToken", response.getAccessToken());
        tokens.put("refreshToken", response.getRefreshToken());
        return tokens;
    }
}

 

Greg-DB
Dropbox Staff

Thanks! So it looks like you're hitting this error condition in the Dropbox Java SDK when calling finishFromRedirect here:

DbxAuthFinish response = pkceWebAuth.finishFromRedirect(redirectUri, new DbxStandardSessionStore(request.getSession(), sessionKey), request.getParameterMap());

This occurs when DbxStandardSessionStore.get returns null, which relies on the passed in session and sessionKey. It looks like you are passing in the same sessionKey, so the issue may be with the session itself.

 

Is there any reason the session in your web app's session may not be persisting that attribute? You may want to print out the session, or step through with a debugger to inspect the DbxStandardSessionStore/HttpServletRequest/HttpSession. Be sure to redact any sensitive values from any output you share here of course.

 

Need more support?