Integrate SharePoint Office 365 into .net core project - sharepoint-online

I would like to share some bit of experience and troubles that I met while doing a folder creation and moving by using RESTful API.

**Create a Folder: **
You will need sharePoint Token
public async Task<JObject> getSharePointToken()
{
var sharPointTokenRequestUrl = "https://accounts.accesscontrol.windows.net/" + _configuration["MicrosoftGraph: TenantId"] + "/tokens/OAuth/2";
var parameters = new Dictionary<string, string>();
parameters["grant_type"] = "client_credentials";
parameters["client_id"] = "your client id";
parameters["client_secret"] = "your client secret";
parameters["resource"] = "resource id";
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointTokenRequestUrl))
{
var response = await httpClient.PostAsync(sharPointTokenRequestUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Also You will need XRequest Digest
public async Task<JObject> getXRequestDigest()
{
var sharPointXRequestDigesttUrl = "https://your site /_api/contextinfo";
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var parameters = new Dictionary<string, string>();
var par = new FormUrlEncodedContent(parameters);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
using (var request = new HttpRequestMessage(new HttpMethod("POST"), sharPointXRequestDigesttUrl))
{
var response = await httpClient.PostAsync(sharPointXRequestDigesttUrl, par);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
return result;
}
}
}
Then you could Crate Folder In SharePoint
namespace Sharepoint.Dtos
{
public class SharePointTokenDto
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string not_before { get; set; }
public string expires_on { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
}
public async Task<Boolean> CrateFolderInSharePoint(string folderPath)
{
var sharePointTokenString = getSharePointToken().Result.ToString();
var sharePointToken = JsonConvert.DeserializeObject<SharePointTokenDto>(sharePointTokenString);
var xRequestDigest = await getXRequestDigest();
var FormDigestValue = xRequestDigest["d"]["GetContextWebInformation"]["FormDigestValue"];
var siteUrl = "https://yoursites-url/sites/SiteName/_api/web/folders";
var folderUrl = "/sites/SiteName/Shared Documents" + folderPath;
var body = new Dictionary<string, string>
{
{ "ServerRelativeUrl", folderUrl }
};
string bodyString = JsonConvert.SerializeObject(body);
bodyString.Insert(0, " \"__metadata\": { \"type\": \"SP.Folder\" } ");
var content = new StringContent(bodyString, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + sharePointToken.access_token);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
httpClient.DefaultRequestHeaders.Add("X-RequestDigest", FormDigestValue.ToString());
using (var request = new HttpRequestMessage(new HttpMethod("POST"), siteUrl))
{
var response = await httpClient.PostAsync(siteUrl, content);
string responseBody = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(responseBody);
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
return false;
}
}
}
}

Related

How to pass token from Nodejs to backend Java code

I am new to Nodejs .
I am trying to pass JWT token from Nodejs to java service class.
I am getting JWT token in a variable in Nodejs code that I need to pass to spring mvc application service class.
can anyone please help me on this?
And having confusion with how to integrate Nodejs with java if i pass variable from Nodejs to java?
Node code is,
module.exports = {
verifyReq: function (req, res, next) {
if (req.headers.authorization) {
res.setHeader('Content-Type', 'text/html');
res.write('<div id="_mscontent"><script src="URL"></script>');
var notAuthorized = false;
var authorization = req.headers.authorization;
console.log("authorization: " + authorization);
if (authorization) {
req.isAuthorized = true;
}
try {
var decodedJWT = JWT.decode(authorization.split(' ')[1], "", true);
} catch (e) {
notAuthorized = true;
}
else {
req.isAuthorized = false;
res.status(401);
res.end('Not Authorized!');
return;
}
return req.isAuthorized === true;
}
};
Java Code,
public class GetCarAssetValuesService {
private static String output;
private static String token;
private static Asset[] myObjects;
public void getAssets(String tokenToPass)
throws JsonParseException, JsonMappingException, IOException, JSONException {
System.out.println("In service");
HttpsURLConnection myURLConnection = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
StringBuilder strBuilder = new StringBuilder();
JSONObject jsonObj = new JSONObject(tokenToPass);
System.out.println("success_token= " + jsonObj);
token = jsonObj.getString("access_token");
System.out.println("Print token= " + token);
try {
URL url = new URL(
"Third Party URL");
myURLConnection = (HttpsURLConnection) url.openConnection();
String bearerAuth = "Bearer " + token;
myURLConnection.setRequestProperty("Authorization", bearerAuth);
myURLConnection.setRequestMethod("GET");
myURLConnection.setRequestProperty("Content-Type", "application/json");
myURLConnection.setDoOutput(true);
inputStream = myURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
bufferedReader = new BufferedReader(inputStreamReader);
if (myURLConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + myURLConnection.getResponseCode());
}
System.out.println("Here the control cars...");
System.out.println("Output from Server .... \n");
while ((output = bufferedReader.readLine()) != null) {
strBuilder.append(output);
System.out.println(output);
}
myURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String mindsphereResponse = strBuilder.toString();
System.out.println("Responsesssssss" + mindsphereResponse);
ObjectMapper mapper = new ObjectMapper();
myObjects = mapper.readValue(mindsphereResponse, Asset[].class);
}
Here instead of passing "tokenToPass" i want to get this token from node js i.e.decodeJWT. This "tokenToPass" i am getting from other java service now i want it from Nodejs.
Thanks in Advance..!!!
You can set the JWT token in the HTTP Request header ( nodejs ) and API endpoint ( java ) can be get it from there.
HelloController.java
#Controller
public class HomeController {
#Autowire
private HomeService homeService;
#GetMapping("/hello")
public String home(HttpServletRequest request, Model model) {
helloService.invoke(request.getHeader('JWT_TOKEN_KEY'));
}
}
HelloService.java
#Service
public class HelloService {
public void invoke(jwtToken) {
// Use this jwttoken
}
}
NodeJS.js
var options = {
host: 'your_java_api_endpoint',
port: 80,
path: '/hello',
headers:{
'JWT_TOKEN_KEY':'json web token here'
}
};
http.get(options, function(res) {
res.on("data", function(responseData) {
console.log("data: " + responseData);
});
}).on('error', function(e) {
console.log("http error : " + e);
});

Azure Graph API is not responding

I am trying to call Azure Graph API to update the user details, I have verified the access to graph api from my Application in Azure. Below is my code
public async Task<HttpResponseMessage> UpdateUserDetails(string userId, string requestString)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException("You must spectify a valid user Id", nameof(userId));
}
if(string.IsNullOrWhiteSpace(requestString))
{
return null;
}
var authContext = new AuthenticationContext(AzureAdConfig.Authority);
var getAccessToken = await authContext.AcquireTokenAsync(AzureAdConfig.GraphResourceId, new ClientCredential(AzureAdConfig.AppId, AzureAdConfig.AppKey));
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", getAccessToken.AccessToken);
string url = AzureAdConfig.GraphResourceId + AzureAdConfig.Tenant + "/users/" + userId + "?" + AzureAdConfig.GraphVersion;
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), url);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", getAccessToken.AccessToken);
request.Content = new StringContent(requestString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
return response;
}
Thanks in Advance
According to my test, you can not get HttpResponseMessage with await client.SendAsync(request) in console application. You should use client.SendAsync(request).Result to get HttpResponseMessage. This my code.
static void Main(string[] args)
{
Console.WriteLine( CallWebApiProtected("2778d832-402f-4bc2-aa28-0720c92947d5"));
Console.Read();
}
static HttpResponseMessage CallWebApiProtected(string userId)
{
string authority = "https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/oauth2/token"; //token endpoint https://login.microsoftonline.com/b29343ba-***/oauth2/token
string resourceUri = "https://graph.windows.net/";
string clientId = "6187f317-5f3c-447e-b0c4-1fd7c31ec14e";//your application id
string clientkey = "q6e2d7xPwfa5rWHDCV5Tv/75wVkAnsinAcgF5FFkf7Y=";//your app key
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, clientkey);
AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientCredential).Result;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Specify values for the following required parameters
queryString["api-version"] = "1.6";
// Specify values for path parameters (shown as {...})
var uri = "https://graph.windows.net/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/users/" +userId + "?" + queryString;
Console.WriteLine(uri);
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(uri);
//request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Bearer " + authenticationResult.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
return response;
}
Its result as below.
Besides,you can get HttpResponseMessage with await client.SendAsync(request) in web application. This my code.
public async System.Threading.Tasks.Task<ActionResult> About()
{
HttpResponseMessage response = await CallWebApiProtected("2778d832-402f-4bc2-aa28-0720c92947d5");
ViewBag.Message = response;
return View();
}
static async System.Threading.Tasks.Task<HttpResponseMessage> CallWebApiProtected(string userId)
{
string authority = "https://login.microsoftonline.com/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/oauth2/token"; //token endpoint https://login.microsoftonline.com/b29343ba-***/oauth2/token
string resourceUri = "https://graph.windows.net/";
string clientId = "6187f317-5f3c-447e-b0c4-1fd7c31ec14e";//your application id
string clientkey = "q6e2d7xPwfa5rWHDCV5Tv/75wVkAnsinAcgF5FFkf7Y=";//your app key
AuthenticationContext authContext = new AuthenticationContext(authority);
ClientCredential clientCredential = new ClientCredential(clientId, clientkey);
AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(resourceUri, clientCredential).Result;
Console.WriteLine("--------------------------------");
Console.WriteLine(authenticationResult.AccessToken);
Console.WriteLine("----------------------------");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Specify values for the following required parameters
queryString["api-version"] = "1.6";
// Specify values for path parameters (shown as {...})
var uri = "https://graph.windows.net/e4c9ab4e-bd27-40d5-8459-230ba2a757fb/users/" + userId + "?" + queryString;
Console.WriteLine(uri);
using (var request = new HttpRequestMessage())
{
request.Method = HttpMethod.Get;
request.RequestUri = new Uri(uri);
//request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
request.Headers.Add("Authorization", "Bearer " + authenticationResult.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
return response;
}
}
Its result as below.

How to catch an exception from Azure Mobile App Backend?

In my Azure Mobile App backend, I have a validation for the data in a post method. In certains circunstances, the backend server throw an exception, but, in the app side, I can't get catch this exception. How can I do that?
That's my method
// POST tables/Paciente
public async Task<IHttpActionResult> PostPaciente(Paciente novoPaciente)
{
//other things
if (paciente != null)
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Já existe um paciente com esse token cadastrado.")
};
//throw new HttpResponseException(responseMessage);
return InternalServerError(new Exception("Já existe um paciente com esse token cadastrado."));
}
}
I tried throw HttpResponseException and return InternalServerException, but none works.
You need to check the status code of the response to your http call (there should be a IsSuccesStatusCode property to check).
I recommend using EnsureSuccessStatusCode() which exists in the HttpResponseMessage class. This method will throw an exception if the StatusCode is not OK (or some variant of a 200-level status code).
Below is a generic class, BaseHttpClientServices, that I use for making REST API requests in all of my projects. It follows all of the best practices for using HttpClient like Reusing HttpClient, Deserializing JSON using Stream, and using ConfigureAwait(false).
Sending A Post Request in Xamarin.Forms
public abstract class HttpClientServices : BaseHttpClientServices
{
const string apiUrl = "your api url";
public static void PostPaciente(Paciente novoPaciente)
{
try
{
var response = await PostObjectToAPI(apiUrl, novoPaciente);
response.EnsureSuccessStatusCode();
}
catch(Exception e)
{
//Handle Exception
}
}
}
Generic HttpClient Implementation
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using Newtonsoft.Json;
using Xamarin.Forms;
namespace NameSpace
{
public abstract class BaseHttpClientService
{
#region Constant Fields
static readonly Lazy<JsonSerializer> _serializerHolder = new Lazy<JsonSerializer>();
static readonly Lazy<HttpClient> _clientHolder = new Lazy<HttpClient>(() => CreateHttpClient(TimeSpan.FromSeconds(60)));
#endregion
#region Fields
static int _networkIndicatorCount = 0;
#endregion
#region Properties
static HttpClient Client => _clientHolder.Value;
static JsonSerializer Serializer => _serializerHolder.Value;
#endregion
#region Methods
protected static async Task<T> GetObjectFromAPI<T>(string apiUrl)
{
using (var responseMessage = await GetObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<T>(responseMessage).ConfigureAwait(false);
}
protected static async Task<HttpResponseMessage> GetObjectFromAPI(string apiUrl)
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.GetAsync(apiUrl).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
protected static async Task<TResponse> PostObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PostObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PostObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Post, apiUrl, requestData);
protected static async Task<TResponse> PutObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PutObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PutObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(HttpMethod.Put, apiUrl, requestData);
protected static async Task<TResponse> PatchObjectToAPI<TResponse, TRequest>(string apiUrl, TRequest requestData)
{
using (var responseMessage = await PatchObjectToAPI(apiUrl, requestData).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> PatchObjectToAPI<T>(string apiUrl, T requestData) => SendAsync(new HttpMethod("PATCH"), apiUrl, requestData);
protected static async Task<TResponse> DeleteObjectFromAPI<TResponse>(string apiUrl)
{
using (var responseMessage = await DeleteObjectFromAPI(apiUrl).ConfigureAwait(false))
return await DeserializeResponse<TResponse>(responseMessage).ConfigureAwait(false);
}
protected static Task<HttpResponseMessage> DeleteObjectFromAPI(string apiUrl) => SendAsync<object>(HttpMethod.Delete, apiUrl);
static HttpClient CreateHttpClient(TimeSpan timeout)
{
HttpClient client;
switch (Device.RuntimePlatform)
{
case Device.iOS:
case Device.Android:
client = new HttpClient();
break;
default:
client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip });
break;
}
client.Timeout = timeout;
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
static async Task<HttpResponseMessage> SendAsync<T>(HttpMethod httpMethod, string apiUrl, T requestData = default)
{
using (var httpRequestMessage = await GetHttpRequestMessage(httpMethod, apiUrl, requestData).ConfigureAwait(false))
{
try
{
UpdateActivityIndicatorStatus(true);
return await Client.SendAsync(httpRequestMessage).ConfigureAwait(false);
}
catch (Exception e)
{
Report(e);
throw;
}
finally
{
UpdateActivityIndicatorStatus(false);
}
}
}
static void UpdateActivityIndicatorStatus(bool isActivityIndicatorDisplayed)
{
if (isActivityIndicatorDisplayed)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = true);
_networkIndicatorCount++;
}
else if (--_networkIndicatorCount <= 0)
{
Device.BeginInvokeOnMainThread(() => Application.Current.MainPage.IsBusy = false);
_networkIndicatorCount = 0;
}
}
static async ValueTask<HttpRequestMessage> GetHttpRequestMessage<T>(HttpMethod method, string apiUrl, T requestData = default)
{
var httpRequestMessage = new HttpRequestMessage(method, apiUrl);
switch (requestData)
{
case T data when data.Equals(default(T)):
break;
case Stream stream:
httpRequestMessage.Content = new StreamContent(stream);
httpRequestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
break;
default:
var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(requestData)).ConfigureAwait(false);
httpRequestMessage.Content = new StringContent(stringPayload, Encoding.UTF8, "application/json");
break;
}
return httpRequestMessage;
}
static async Task<T> DeserializeResponse<T>(HttpResponseMessage httpResponseMessage)
{
httpResponseMessage.EnsureSuccessStatusCode();
try
{
using (var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var reader = new StreamReader(contentStream))
using (var json = new JsonTextReader(reader))
{
if (json is null)
return default;
return await Task.Run(() => Serializer.Deserialize<T>(json)).ConfigureAwait(false);
}
}
catch (Exception e)
{
Report(e);
throw;
}
}
static void Report(Exception e, [CallerMemberName]string callerMemberName = "") => Debug.WriteLine(e.Message);
#endregion
}
}

I need authorization signature code for file download from Blob Storage .Using Rest API

My Authentication code is i thing i might be wrong.
I attached my code please refer
private const string FileDownloadURL =
"https://{0}.blob.core.windows.net/{1}/{2}";
public async Task<string> DownloaDFileToBlob(string blobname, string downloadpath, string filename)
{
string Requesturl = string.Format(FileDownloadURL, storageAccount, blobname, filename);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Requesturl);
string now = DateTime.UtcNow.ToString("R");
string exp = DateTime.UtcNow.AddDays(1).ToString("R");
request.Method = "GET";
request.Headers.Add("x-ms-version", "2015-12-11");
request.Headers.Add("x-ms-date", now);
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.Headers.Add("Authorization", AuthorizationHeader3(now, exp,storageAccount, blobname, filename));
var response = await request.GetResponseAsync();
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
return resp.StatusCode.ToString();
}
}
My Authentication Header add method
private string AuthorizationHeader3(string method, string now, HttpWebRequest request, string storageAccount, string storageKey, string containerName,string filename)
{
string headerResource = $"x-ms-date:{now}\nx-ms-version:2015-12-11";
string canonicalizedResource = $"/{storageAccount}/{containerName}/{filename}\ncomp:metadata\nrestype:container\ntimeout:20";
var contentEncoding = "";
var contentLanguage = "";
var contentLength = "";
var contentMd5 = "";
var contentType = "";
var date = "";
var ifModifiedSince = "";
var ifMatch = "";
var ifNoneMatch = "";
var ifUnmodifiedSince = "";
var range = "";
var stringToSign = $"{method}\n{contentEncoding}\n{contentLanguage}\n{contentLength}\n{contentMd5}\n{contentType}\n{date}\n{ifModifiedSince}\n{ifMatch}\n{ifNoneMatch}\n{ifUnmodifiedSince}\n{range}\n{headerResource}\n{canonicalizedResource}";
var signature = "";
using (var hmacSha256 = new HMACSHA256(Convert.FromBase64String(storageKey)))
{
var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String AuthorizationHeader = String.Format("{0} {1}:{2}", "SharedKey", storageAccount, signature);
return AuthorizationHeader;
}
According to the Get blob API
https://myaccount.blob.core.windows.net/mycontainer/myblob
the canonicalizedResource should be $"/{storageAccount}/{containerName}/{blobName} not
$"/{storageAccount}/{containerName}/{filename}\ncomp:metadata\nrestype:container\ntimeout:20";
Please have a try to use the following demo code to download the blob. It works correctly on my side.
var account = "storageAccount";
var accountKey = "account key";
var container = "container name";
var blobName = "blob name";
var apiVersion = "2015-12-11";
var blobUrl = $"https://{account}.blob.core.windows.net/{container}/{blobName}";
var method = "GET";
var now = DateTime.UtcNow.ToString("R");
var canonicalizedHeaders = $"x-ms-date:{now}\nx-ms-version:{apiVersion }";
var canonicalizedResource = $"/{account}/{container}/{blobName}";
var stringToSign = $"{method}\n\n\n\n\n\n\n\n\n\n\n\n{canonicalizedHeaders}\n{canonicalizedResource}";
var auth = CreateAuthString(account, stringToSign, accountKey);
Uri uri = new Uri(blobUrl);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("x-ms-date", now);
client.DefaultRequestHeaders.Add("x-ms-version", "2015-12-11");
client.DefaultRequestHeaders.Add("Authorization", auth);
HttpResponseMessage response = client.SendAsync(request).Result;
var status = response.IsSuccessStatusCode;
private static string CreateAuthString(string blobStorageAccount, string signStr, string blobStorageAccessKey)
{
string signature;
byte[] unicodeKey = Convert.FromBase64String(blobStorageAccessKey);
using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
{
byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(signStr);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
var authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
blobStorageAccount,
signature);
return authorizationHeader;
}

modify/update the redirectUri?

private static async Task CreateApplication(string tenantId, string
clientId, string redirectUri)
{
var graphUri = new Uri("https://graph.windows.net");
var serviceRoot = new Uri(graphUri, tenantId);
var activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => AcquireTokenAsyncForUser("https://login.microsoftonline.com/"
+
tenantId, clientId, redirectUri));
var app = new Application
{
Homepage = "https://localhost",
DisplayName = "My Application",
LogoutUrl = "https://localhost",
IdentifierUris = new List<string> {
"https://tenant.onmicrosoft.com/MyApp" },
ReplyUrls = new List<string> { "https://localhost" }
};
await activeDirectoryClient.Applications.AddApplicationAsync(app);
Console.WriteLine(app.ObjectId);
}

Resources