403 Forbidden Error Accessing Google Drive Images via Frontend API

37 Views Asked by At

I am encountering an issue with images uploaded to Google Drive from the frontend of my application. I have an endpoint that accepts a MultipartFile object, which is then used to upload an image to Google Drive. The response from this operation includes a fileLink that points directly to the image. Here's an example link generated by my endpoint: https://drive.google.com/uc?id=1Qx2ZSGL-9clSvEb0VGHD4ojxemW8NUyg.

When I manually paste this link into a browser, the image displays without any issues. However, when I try to access the image via my frontend API, I get a 403 Forbidden error.

Why is this happening? Below is the snippet of code responsible for the entire process:

    public FileDetails uploadFileAndGetLink(String jws, MultipartFile multipartFile) throws FileOperationException {
        com.google.api.services.drive.model.File file = uploadFile(jws, multipartFile);
        String webContentLink = file.getWebContentLink().replace("&export=download", "");
        return FileDetails.builder().fileId(file.getId()).fileLink(webContentLink).build();
    }

    protected File uploadFile(String jws, MultipartFile file) throws IOException, GeneralSecurityException {
        File fileMetadata = new File();
        fileMetadata.setName(file.getOriginalFilename());
        InputStreamContent mediaContent = new InputStreamContent(
                file.getContentType(),
                new ByteArrayInputStream(file.getBytes()));
        return executeFileUpload(jws, fileMetadata, mediaContent);
    }

    private File executeFileUpload(String jws, File fileMetadata, AbstractInputStreamContent mediaContent)
            throws IOException, GeneralSecurityException {
        File file = getDriveService(jws).files().create(fileMetadata, mediaContent)
                .setFields("id, thumbnailLink")
                .execute();
        Permission permission = new Permission();
        permission.setType("anyone");
        permission.setRole("reader");
        permission.setAllowFileDiscovery(true);
        getDriveService(jws).permissions().create(file.getId(), permission).execute();
        return getDriveService(jws).files().get(file.getId()).setFields("id, webContentLink").execute();
    }

    private Drive getDriveService(String jws) throws IOException, GeneralSecurityException {
        return googleDriveCommons.getService(jws);
    }

error 403 forbidden

I've checked my Google Drive API permissions and ensured that the images are publicly accessible. Despite this, I'm still facing the forbidden error on the frontend side. Is there something I'm missing in the process of sharing or accessing these images programmatically?

Any insights or suggestions on how to resolve this issue would be greatly appreciated.

0

There are 0 best solutions below