I have an App engine application. I want to use Cloud Storage to store some user-uploaded files.
I want to know how to do simple authentication to access the single, free bucket that comes with every app engine application.
I want only the application itself to talk to Cloud storage, and the user need not have any interaction with Cloud storage. Every file can be placed in the same folder and it needs to be accessible only to the App engine JVM.
Is there a simple way for the authentication, without going through Oauth2 etc.? A simple server-to-server sort of access, if its possible!
Edit: Is it the same as this?
gcloud beta auth application-default login
Edit 2: Tried the above default authentication setup for Gcloud. Still the same exception is thrown.
com.google.cloud.storage.StorageException: Invalid Credentials
Testing code that I am using:
private static Storage storage = null;
static {
storage = StorageOptions.getDefaultInstance().getService();
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
out.println("Hello, world");
testCloudStorage();
}
private void testCloudStorage() throws IOException{
ByteArrayInputStream baIs = new ByteArrayInputStream("TEST FILE CONTENT".getBytes());
uploadFile("test-content.txt", baIs, "xyzabc.appspot.com");
}
/**
* Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
* environment variable, appending a timestamp to end of the uploaded filename.
*/
public String uploadFile(String fileName, InputStream inputStream, final String bucketName) throws IOException {
DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
DateTime dt = DateTime.now(DateTimeZone.UTC);
String dtString = dt.toString(dtf);
final String extendedFileName = fileName + dtString;
// the inputstream is closed by default, so we don't need to close it here
BlobInfo blobInfo =
storage.create(
BlobInfo
.newBuilder(bucketName, extendedFileName)
// Modify access list to allow all users with link to read file
.setAcl(new ArrayList<>(Arrays.asList(Acl.of(Acl.User.ofAllUsers(), Role.READER))))
.build(),
inputStream);
// return the public download link
return blobInfo.getMediaLink();
}
Edit 3: These are the steps I followed:
- I have a basic working JSP sample application - both devserver and deployed version are working okay
- DataStore is working - insert/update/delete
- I added the sample code for Cloud Storage following this tutorial
- I followed this tutorial for installing GCloud SDK and doing init and setting the default auth