modify/update the redirectUri? - c#-4.0

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);
}

Related

Integrate SharePoint Office 365 into .net core project

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;
}
}
}
}

timer triggered azure function not working - dynamic plan

I have below code in azure function which is timer triggered. All it does is creates a logs in azure via service principal method and calls Azure APIs to stand up resources.
Functions logs until "logging in". Doesn't go any further and don't log either logging succeed or failed. What I'm missing?
module.exports = function (context, myTimer) {
var timeStamp = new Date().toISOString();
context.log("time triggered function entry")
const ACI = require('azure-arm-containerinstance');
const AZ = require('ms-rest-azure');
context.log('Starting a container');
if(process.env.AZURE_CLIENT_ID) {
var client_id = process.env.AZURE_CLIENT_ID;
}
else {
var client_id = "";
}
if(process.env.AZURE_CLIENT_SECRET) {
var client_secret = process.env.AZURE_CLIENT_SECRET;
}
else {
var client_secret = "";
}
if(process.env.TENANT_ID) {
var tenant_id = process.env.TENANT_ID;
}
else {
var tenant_id = "";
}
if(process.env.SUBSCRIPTION_ID) {
var subscription_id = process.env.SUBSCRIPTION_ID;
} else {
var subscription_id = "";
}
if(process.env.RESOURCE_GROUP) {
var resource_group = process.env.RESOURCE_GROUP;
} else {
var resource_group = "testAppDeployment";
}
if(process.env.CONTAINER_IMAGE_NAME) {
var containerImageName = process.env.CONTAINER_IMAGE_NAME;
} else {
var containerImageName = "<some-containername";
}
if(process.env.DEFAULT_REGION) {
var location = process.env.DEFAULT_REGION;
} else {
var location = "eastus"
}
var containerGroup = resource_group + "containerGroup";
var containerName = "tempname";
context.log("Logging in")
context.log("tenant id: " + tenant_id)
context.log("client id: " + client_id)
context.log("client secret: " + client_secret)
AZ.loginWithServicePrincipalSecret(
client_id,
client_secret,
tenant_id,
(err, credentials) = {
if (err) {
context.log("logging failed")
throw err;
}
let client = new ACI(credentials, subscription_id);
context.log("logging succeeded")
}
}

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.

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;
}

Katana Webserver not finding clientSecret

I downloaded the katana project and wanted to try the client/server in the sandbox project.
I rand into a problem at for OAuthValidateClientAuthenticationContext :
public bool TryGetFormCredentials(out string clientId, out string clientSecret)
{
clientId = Parameters.Get(Constants.Parameters.ClientId);
if (!String.IsNullOrEmpty(clientId))
{
clientSecret = Parameters.Get(Constants.Parameters.ClientSecret);
ClientId = clientId;
return true;
}
clientId = null;
clientSecret = null;
return false;
}
clientSecret is null and hence the following do not validated the client.
private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
context.TryGetFormCredentials(out clientId, out clientSecret))
{
if (clientId == "123456" && clientSecret == "abcdef")
{
context.Validated();
}
else if (context.ClientId == "7890ab" && clientSecret == "7890ab")
{
context.Validated();
}
}
return Task.FromResult(0);
}
Ensure the client_secret param doesn't contain a space in your post
client_secret[space] will fail.

Resources