top of page
Blog Page(1902x420).jpg

Keep your business ahead with

Insights That Drive Innovation

Authorization for Onedrive Graph API




To use the Onedrive API via Microsoft graph we received Client Id and Client secret in Part 1.


Authentication Flow: Code Flow

The code flow for authentication is a three-step process with separate calls to authenticate and authorize the application and to generate an access token to use the OneDrive API. This also allows your application to receive a refresh token that will enable long-term use of the API in some scenarios, to allow access when the user isn't actively using your application.



Step 1: Get the Authorization code

To start the sign-in process with the code flow, use a web browser or web-browser control to load this URL request.

Request Type: GET

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id={client_id}&scope={scope}

&response_type=code&redirect_uri={redirect_uri}


Required query string parameters:

Parameter

Value

Description

client_id

String

The client id created for APP

​scope

​String

A space-separated list of scopes that your app requires

​redirect_uri

String

The redirect URL that the browser is sent to when authentication is complete.

response_type

String

The type of response expected from the authorization flow. For this flow, the value must be codescope

Response:

After we have received the code value, we can redeem this code for a set of tokens that allow us to authenticate with the OneDrive API. To redeem the code, make the following request:


Step 2: Redeem the code for the access tokens

Request Type: POST

https://login.microsoftonline.com/common/oauth2/v2.0/token

Content-Type: application/x-www-form-urlencoded

client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}

&code={code}&grant_type=authorization_code


Required query string parameters:

Parameter

Value

Description

client_id

String

The client id created for APP

scope

String

​A space-separated list of scopes that your app requires

redirect_uri

String

​The redirect URL that the browser is sent to when authentication is complete.

response_type

String

The type of response expected from the authorization flow. For this flow, the value must be codescope

code

String

​The authorization code you received in the first authentication request

Response :

If the call is successful, the response for the POST request contains a JSON string that includes several properties, including access_token, token_type, and refresh_token (if you requested the wl.offline_access scope).

{
  "token_type":"bearer",
  "expires_in": 3600,
  "scope":"wl.basic onedrive.readwrite",
  "access_token":"EwCo...AA==",
  "refresh_token":"eyJh...9323"
}

Step 3: Get the new access token or refresh token

If your app has requested the offline_access scope this step will return a refresh_token that can be used to generate additional access tokens after the initial token has expired.


To redeem the refresh token for a new access token, make the following request:


POST https://login.microsoftonline.com/common/oauth2/v2.0/token

Content-Type: application/x-www-form-urlencoded

client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
&refresh_token={refresh_token}&grant_type=refresh_token

Required query string parameters:

Parameter

Value

Description

​client_id

​String

​The client id created for APP

​redirect_uri

String

​The redirect URL that the browser is sent to when authentication is complete. This should match the redirect_uri value used in the first request.

​client_secret

String

​The client secret created for your application.

refresh_token

String

The refresh token you received previously.

Response :

If the call is successful, the response for the POST request contains a JSON string that includes several properties including access_token, authentication_token and refresh_token if you requested the offline_access scope.

{
  "token_type":"bearer",
  "expires_in": 3600,
  "scope": "wl.basic onedrive.readwrite wl.offline_access",
  "access_token":"EwCo...AA==",
  "refresh_token":"eyJh...9323
}

You can now store and use the access_token to make authenticated requests to Microsoft Graph.

Important: Treat the values of access_token and refresh_token in this response as securely as you would a user's password.



Upload File In OneDrive Storage

The simple upload API allows you to provide the contents of a new file or update the contents of an existing file in a single API call. This method only supports files up to 4MB in size.


Whitelist this URL = https://graph.microsoft.com


HTTP Request To Upload New File:

Method Type: PUT

accessToken = “JAKHJHGjhj547876iinhghjghg….” // Access Token


HttpRequest request = new HttpRequest();

request.setMethod(PUT ); //PUT method

request.setEndpoint(End Point URL);

request.setHeader('Authorization','Bearer'+' '+ accessToken);

request.setHeader('Accept','*/*');


Response:

If successful, this method returns an driveItem resource in the response body for the newly created file.

HTTP/1.1 201 Created
Content-Type: application/json
{"@content.downloadUrl":"https://public-sn3302.files.1drv.com/y2pcT7OaUEExF7EHOlpTjCE55mIUoiX7H3sx1ff6I-nP35XUTBqZlnkh9FJhWb_pf9sZ7LEpEchvDznIbQig0hWBeidpwFkOqSKCwQylisarN6T0ecAeMvantizBUzM2PA1",
  "createdDateTime": "2016-09-16T03:37:04.72Z",
  "cTag": "aYzpENDY0OEYwNkM5MUQ5RDNEITU0OTI3LjI1Ng",
  "eTag": "aRDQ2NDhGMDZDOTFEOUQzRCE1NDkyNy4w",
  "id":"D4648F06C91D9D3D!54927",
  "lastModifiedBy": {
    "user": {
      "displayName": "Daron Spektor",
      "id": "d4648f06c91d9d3d"
    }
  },
  "name":"BritishShorthair.jpg",
  "size":35212,
  "image":{
    "height":398,
    "width":273
  },
  "file": {
    "hashes":{   "sha1Hash":"wmgPQ6jrSeMX7JP1XmstQEGM2fc="     }
 }
 }


Rename File In OneDrive Storage

The presence of the renameAction resource on an itemActivity indicates that the activity renamed an item.


Request:

Method Type: PATCH

End Point URL: https://graph.microsoft.com/v1.0/me/drive/root:/existingFileName


Request Body:

'{"name": "'+newFileName+'"}';  
accessToken = “JAKHJHGjhj547876iinhghjghg….”   // Access Token

HttpRequest request = new HttpRequest();

request.setMethod(PATCH );      //PATCH  method
request.setEndpoint(End Point URL);
request.setHeader('Authorization','Bearer'+' '+ accessToken);
request.setHeader('Accept','*/*');

Response :

{"@content.downloadUrl":"https://public-sn3302.files.1drv.com/y2pcT7OaUEExF7EHOlpTjCE55mIUoiX7H3sx1ff6I-nP35XUTBqZlnkh9FJhWb_pf9sZ7LEpEchvDznIbQig0hWBeidpwFkOqSKCwQylisarN6T0ecAeMvantizBUzM2PA1",
  "createdDateTime": "2016-09-16T03:37:04.72Z",
  "cTag": "aYzpENDY0OEYwNkM5MUQ5RDNEITU0OTI3LjI1Ng",
  "eTag": "aRDQ2NDhGMDZDOTFEOUQzRCE1NDkyNy4w",
  "id":"D4648F06C91D9D3D!54927",
  "lastModifiedBy": {
    "user": {
      "displayName": "Daron Spektor",
      "id": "d4648f06c91d9d3d"
    }
  },
  "name":"BritishShorthair.jpg",
  "size":35212,
  "image":{
    "height":398,
    "width":273
  },
  "file": {
    "hashes":{   "sha1Hash":"wmgPQ6jrSeMX7JP1XmstQEGM2fc="     }
  }
}


Delete File In OneDrive Storage

Delete a DriveItem by using its ID or path. Note that deleting items using this method will move the items to the recycle bin instead of permanently deleting the item.


Whitelist this URL = https://graph.microsoft.com


Permissions:

Permission type Permissions (from least to most privileged)

Delegated (work or school account) Files.ReadWrite, Files.ReadWrite.All, Sites.ReadWrite.All

Delegated (personal Microsoft account) Files.ReadWrite, Files.ReadWrite.All

Application Files.ReadWrite.All, Sites.ReadWrite.All


HTTP Request:

Method Type: DELETE 
End Point URL : https://graph.microsoft.com/v1.0/drive/root:/


Response:

If successful, this call returns a 204 No Content response to indicate that resource was deleted and there was nothing to return.


HTTP/1.1 204 No Content.



Preview File In OneDrive Storage

We have achieved this functionality using two steps in the first step we get the file with the download URL and in the 2nd step we use external system node JS where we can convert the download URL to base64 then we able to preview file


Step 1: Get a file from OneDrive Storage


HTTP Request:

Method Type: GET
End Point URL: https://graph.microsoft.com/v1.0/drive/root:/
accessToken = “JAKHJHGjhj547876iinhghjghg….”   // Access Token

HttpRequest request = new HttpRequest();

        request.setMethod(‘GET’);      //GET method
        request.setEndpoint(End Point URL);
        request.setHeader('Authorization','Bearer'+' '+ accessToken);
        request.setHeader('Accept','*/*');

HTTP Response:

{
  "@content.downloadUrl":"https://public-sn3302.files.1drv.com/y2pcT7OaUEExF7EHOlpTjCE55mIUoiX7H3sx1ff6I-nP35XUTBqZlnkh9FJhWb_pf9sZ7LEpEchvDznIbQig0hWBeidpwFkOqSKCwQylisarN6T0ecAeMvantizBUzM2PA1",
  "createdDateTime": "2016-09-16T03:37:04.72Z",
  "cTag": "aYzpENDY0OEYwNkM5MUQ5RDNEITU0OTI3LjI1Ng",
  "eTag": "aRDQ2NDhGMDZDOTFEOUQzRCE1NDkyNy4w",
  "id":"D4648F06C91D9D3D!54927",
  "lastModifiedBy": {
    "user": {
      "displayName": "Daron Spektor",
      "id": "d4648f06c91d9d3d"
    }
  },
  "name":"BritishShorthair.jpg",
  "size":35212,
  "image":{
    "height":398,
    "width":273
  },
  "file": {
    "hashes":{
      "sha1Hash":"wmgPQ6jrSeMX7JP1XmstQEGM2fc="
    }
  }
}

After getting response we saved download url for used in next step.

We send download url to external system with JWT token.


Step 2: Use Other External System for Create Base64 from download URL.

After getting the download URL and JWT Token we decrypt the Token and convert the download URL to base64 and return to the system.

Whitelist URL = https://fm-outlook-file-preview.uc.r.appspot.com (external system url)

Save this URL in the remote site setting.


Step 3: Use Other External System for Create Base64 from download URL.

After getting base64 from the external system we convert base64 to image and show it the in preview.


Summary:

The Microsoft Graph API for OneDrive allows developers to access and manipulate data stored in OneDrive, including files and folders. To access the API, developers must first obtain an access token through the Azure Active Directory (AAD) authentication process. The token must be included in the header of each API request to authorize the action. Additionally, the developer must also grant permissions to the API to access the specific OneDrive resources they wish to manipulate.

Comments


bottom of page