Issue
I'm writing an application using Spring Boot and Java that will be writing files to Azure Blob Storage. How can I use a Service Principal to authenticate? The details of the SP should ideally be read in via some properties or an external file.
I've been wading through the reams of documentation and examples, all of which don't seem to be quite what I'm looking for. Most examples that I've seen use the Storage Account Key which I don't want to do.
Some example code would be really appreciated. As I said, I'm struggling to find a decent example (both of how to use an SP but also generally how to write to Azure BLOB Storage in Java) as there seems to be so many different ways of accessing storage scattered around in the microsoft docs.
Solution
You can use ADAL4J to acquire a token, and then use the token to write to blobs.
- Add role assignment to your principal.
Get token.
public static String getToken() throws Exception { String TENANT_ID = "your tenant id or name, e4c9*-*-*-*-*57fb"; String AUTHORITY = "https://login.microsoftonline.com/" + TENANT_ID; String CLIENT_ID = "your application id, dc17*-*-*-*a5e7"; String CLIENT_SECRET = "the secret, /pG*32"; String RESOURCE = "https://storage.azure.com/"; String ACCESS_TOKEN = null; ExecutorService service = Executors.newFixedThreadPool(1); AuthenticationContext context = null; try { context = new AuthenticationContext(AUTHORITY, false, service); ClientCredential credential = new ClientCredential(CLIENT_ID, CLIENT_SECRET); Future<AuthenticationResult> future = context.acquireToken(RESOURCE, credential, null); ACCESS_TOKEN = future.get().getAccessToken(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } finally { service.shutdown(); } return ACCESS_TOKEN; }
Access blob.
public static void main(String[] args) throws Exception { String token = getToken(); StorageCredentialsToken credentialsToken = new StorageCredentialsToken("storagetest789", token); CloudBlobClient blobClient = new CloudBlobClient(new URI("https://storagetest789.blob.core.windows.net/"), credentialsToken); CloudBlobContainer blobContainer = blobClient.getContainerReference("pub"); CloudBlockBlob blockBlob = blobContainer.getBlockBlobReference("test.txt"); blockBlob.uploadText("Test!"); }
Hope it helps.
Answered By - Jack Jia