"Insufficient priveleges to complete the operation", inspite of granting all necessary permissions - c#

{"odata.error":{"code":"Authorization_RequestDenied",
"message":
{"lang":"en","value":"Insufficient privileges to complete the operation."},
"requestId":"b205e5d0-f929-418e-9153-f1994e2c0893",
"date":"2020-02-15T06:53:57"}
}
I am able to retrieve the authentication token from the server and have granted all the permissions through the AAD but still I'm facing the same issue.
Would be great if someone could help me out.
I am using the Microsoft Graph API.
Below is the code that I am using
private const string clientID = "XXXX";
private const string addInstance = "https://login.microsoftonline.com/{0}";
private const string tenant = "XYZ";
private const string resource = "https://graph.windows.net";
private const string appKey = "appkey";
static string authority = String.Format(CultureInfo.InvariantCulture, addInstance, tenant);
private static HttpClient httpclient = new HttpClient();
private static AuthenticationContext context = null;
private static ClientCredential credential = null;
static void Main(string[] args)
{
context = new AuthenticationContext(authority);
credential = new ClientCredential(clientID,appKey);
Task<string> token = GetToken();
token.Wait();
Console.WriteLine(token.Result);
Task<string> users = GetUsers(token.Result);
users.Wait();
Console.WriteLine(users.Result);
//Console.ReadLine();
}
private static async Task<string> GetUsers(string result)
{
string users = null;
string queryString = "api-version=1.6";
var uri = "https://graph.windows.net/ *The Microsoft 365 account assosciated with the tenant* /users?"+ queryString;
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result);
var getResult = await httpclient.GetAsync(uri);
if (getResult != null)
{
users = await getResult.Content.ReadAsStringAsync();
}
return users;
}
private static async Task<string> GetToken()
{
AuthenticationResult result = null;
string token = null;
result = await context.AcquireTokenAsync(resource, credential);
token = result.AccessToken;
return token;
}
}

I have tried following way and perfectly worked for me.
//Token Request End Point
string tokenUrl = $"https://login.microsoftonline.com/yourTenant.onmicrosoft.com/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
//I am Using client_credentials as It is mostly recommended
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = "b603c7be-a956_Your_Client_Id_a45996-e6921e61f36955",
["client_secret"] = "Vxf1SluKbgu4PF0loj_Your_Client_Secret_okjh8wL/yujh45lojhgg=",
["resource"] = "https://graph.windows.net"
});
dynamic json;
AccessTokenClass results = new AccessTokenClass();
HttpClient client = new HttpClient();
var tokenResponse = await client.SendAsync(tokenRequest);
json = await tokenResponse.Content.ReadAsStringAsync();
results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
//New Block For Accessing Data from Microsoft Graph Rest API
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.windows.net/YourTenant.onmicrosoft.com/users?api-version=1.6"));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
//Check The Response and extract response data
HttpResponseMessage response = await _client.SendAsync(request);
dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
return objGpraphUserList
Class Used:
public class AccessTokenClass
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}
I got the User List as expected. See the screen shot.
Validate Your Token :
Check your token on https://jwt.io/ which should have User.ReadWrite.All or User.Read.All Application permission
Note:
You should have following permission on Azure Active Directory Graph
For more information please refer to this official document
Hope this would help.

Related

How to access Sharepoint files using app-level authentication / access token?

I am trying to access Sharepoint files without having to have the user login.
I can get an access token by either
Method 1:
var client = new RestClient("https://login.microsoftonline.com/app's-tenant-id-here/oauth2/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Cookie", "fpc=AjMRWuGtzbFJgrxV0V1kMCkUHKO3AQAAAEqqRtgOAAAA");
request.AddParameter("resource", "https://graph.microsoft.com");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "client-id-here");
request.AddParameter("client_secret", ".client-secret-here");
IRestResponse response = client.Execute(request);
or Method 2 -
(This one gives the following error: The type initializer for 'AppForSharePointOnlineWebToolkit.TokenHelper' threw an exception.)
string siteUrl = "https://the-site-I-am-trying-to-access.sharepoint.com/sites/xxx/";
string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));
string accessToken2 = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
using (ClientContext cc = TokenHelper.GetClientContextWithAccessToken(siteUrl, accessToken2))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
}
And even method 3
HttpWebRequest endpointRequest = (HttpWebRequest)WebRequest.Create("https://the-site-I-am-trying-to-access.sharepoint.com/sites/xxx/_api/web/getfilebyserverrelativeurl('~/Shared%20Documents/picture.png')");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
None of which successfully access Sharepoint.
So my question is, am I doing something wrong or is there another way to achieve this?
Well, first of all I would suggest to use Graph API if possible. At least it's the preferred way to query data and it makes things a lot easier.
To access data inside the Microsoft 365 world via Graph API it's required to create a new app registration inside the azure portal > Azure Active Directory > App Registrations.
See this link for more information: MS Docs App Registration
After you've created a new app, configure the required scope and permissions to access SharePoint data (e.g. Sites.ReadWrite.All for full access).
After that simply use the generated and provided clientID, clientSecret, tenantID and scope to request a new access token.
I created a Class to carry out all the http requests for me:
public class GraphClient
{
private const string LOGIN_URL = "https://login.microsoftonline.com/{0}/oauth2/v2.0/token";
private const string BASE_URL = "https://graph.microsoft.com";
protected internal string HttpBaseAddress { get; }
protected internal readonly HttpClient HttpClient;
public GraphClient(string tenantId, string clientId, string clientSecret, string version = "1.0")
{
var msgHandler = new GraphAuthMessageHandler(string.Format(LOGIN_URL, tenantId),
$"{BASE_URL}/.default",
clientId,
clientSecret,
new HttpClientHandler());
HttpBaseAddress = $"{BASE_URL}/v{version}/";
HttpClient = new HttpClient(msgHandler)
{
BaseAddress = new Uri(HttpBaseAddress),
Timeout = new TimeSpan(0, 2, 0)
};
HttpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
HttpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");
HttpClient.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"*\"");
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
The provided MessageHangler requests the token and adds the provided access token to the header:
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
public class GraphAuthMessageHandler : DelegatingHandler
{
private readonly string _loginUrl;
private readonly string _clientId;
private readonly string _clientSecret;
private readonly string _scope;
public GraphAuthMessageHandler(string loginUrl, string scope, string clientId, string clientSecret, HttpMessageHandler innerHandler)
: base(innerHandler)
{
_loginUrl = loginUrl;
_clientId = clientId;
_clientSecret = clientSecret;
_scope = scope;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var result = await AcquireAccessToken();
request.Headers.Authorization = new AuthenticationHeaderValue(result.TokenType, result.AccessToken);
return await base.SendAsync(request, cancellationToken);
}
private async Task<AuthResponse> AcquireAccessToken()
{
var httpClient = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new("client_id", _clientId),
new("client_secret", _clientSecret),
new("scope", _scope),
new("grant_type", "client_credentials")
};
var response = await httpClient.PostAsync(_loginUrl, new FormUrlEncodedContent(values));
return await response.Content.ReadFromJsonAsync<AuthResponse>();
}
}
Edit Here's the AuthResponse class, that simply maps the json response to an C# Object:
using System.Text.Json.Serialization;
public class AuthResponse
{
[JsonPropertyName("token_type")] public string TokenType { get; set; }
[JsonPropertyName("expires_in")] public int ExpiresIn { get; set; }
[JsonPropertyName("access_token")] public string AccessToken { get; set; }
}
And then simply use it:
var driveId = "your-drive-id-here";
var itemId = "your-item-id-here";
var client = new GraphClient(TENANT_ID, CLIENT_ID, CLIENT_SECRET);
var response = await client.HttpClient.GetAsync($"drives/{driveId}/items/{itemId}/content");
if (response.IsSuccessStatusCode)
{
var fileStream = await response.Content.ReadAsStreamAsync();
// do something with stream
}
// handle errors here
The Microsoft Docs are a good start to get it working, it helped me a lot about using Graph API and also the Graph Explorer to test queries and requests to the endpoint.
P.S. this is just a simple example and for sure there's room for improvements, but this will hopefully point you to the right direction ;)

Get requests to api stuck on pending

I apologize in advance for the bad editing skills, I'm new at posting questions
I'm trying to call my c# api from an angular app, however the request is stuck on pending. I don't think theres a mistake in my typescript code but I'm new to c# so it might be something to do with the api, possibly because of the asyncs.
Here's the api code
{
private static readonly string Tenant = "https://login.microsoftonline.com/{azure.tenant}/";
private static readonly string Resource = "https://analysis.windows.net/powerbi/api";
private string getToken()
{
var authContext = new AuthenticationContext(Tenant);
var clientCredential = new ClientCredential(AppId, AppSecret);
var token = authContext.AcquireTokenAsync(Resource, clientCredential);
return token.Result.AccessToken;
}
private PowerBIClient getPBIClient()
{
var token = new TokenCredentials(getToken(), "Bearer");
return new PowerBIClient(new Uri("https://api.powerbi.com/"), token);
}
public async Task<ODataResponseListReport> getReportsAsync(string ws)
{
PowerBIClient pbiClient = getPBIClient();
var reports = await pbiClient.Reports.GetReportsInGroupAsync(ws);
return reports;
}
public async Task<ReportEmbeddingData> getReportEmbeddingDataAsync(string ws, string rep)
{
PowerBIClient pbiClient = getPBIClient();
var report = await pbiClient.Reports.GetReportInGroupAsync(ws, rep);
var embedUrl = report.EmbedUrl;
var reportName = report.Name;
GenerateTokenRequest genTokenReqParam = new GenerateTokenRequest(accessLevel: "view");
string embedToken = (await pbiClient.Reports.GenerateTokenInGroupAsync(ws, rep, genTokenReqParam)).Token;
return new ReportEmbeddingData {
reportId = rep,
reportName = reportName,
embedUrl = embedUrl,
accessToken = embedToken
};
}
}
And here is my angular call that's being done on ngOnInit
getReports(){
this.http.get("http://localhost:44391/api/Auth?ws="+this.workspaceId)
.subscribe((response) => {
this.reportArray = response;
console.log(this.reportArray);
});
}

Not getting all users from the AAD when trying to get user list by using MSGrpah API

Here is my code which is pulling only 100 users from the active directory. I have granted the "read all user profile permission" in application and delegated sections as well.
namespace MVCDemoGraphAPI.Controllers
{
public class HomeController : Controller
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
public async Task<string> Users()
{
string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
AuthenticationContext authContext = new AuthenticationContext(authority);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync("https://graph.microsoft.com",
new ClientCredential(clientId, appKey));
}
catch (Exception)
{
throw;
}
//Now call the Graph API
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/users");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
string output = await response.Content.ReadAsStringAsync();
return output;
}
}
}
You have to use Paging filters as described in here:
https://learn.microsoft.com/en-us/previous-versions/azure/ad/graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options ,
mainly paging forward.
I recommend to use c# graph client Nuget and then use the code below:
var users = await graphClient.Users.Request().GetAsync();
try
{
while (users != null)
{
var usersList = users.CurrentPage.ToList();
count = count + usersList.Count();
users = await users.NextPageRequest.GetAsync();
}
}
catch
{
//
}

How to cache a request in ASP.NET Core?

I am looking for how to cache a request in ASP.NET Core 2.x?
I have API proxy which always return a different response using the same request (synonyms composition using an AI, hence that's why I am not looking for caching the response).
And I would like to cache the request since it's always the same (always the same basic auth and parameters to poke the other API that I am proxy-ing).
Since the request use a file input.xml for the parameters, I am wondering where I can cache that one as well
My controller:
[Route("api/v1/[controller]")]
public class CompositionController : Controller
{
[HttpGet]
public async Task<string> Get(string transformation = "xml")
{
var httpClient = new HttpClient();
const string authScheme = #"Basic";
const string name = #"myUserName";
const string password = #"myPassword";
var authBytes = Encoding.ASCII.GetBytes($#"{name}:{password}");
var auth64BaseString = Convert.ToBase64String(authBytes);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth64BaseString);
const string fileName = #"input.xml";
var inputBytes = File.ReadAllBytes(fileName);
var byteArrayContent = new ByteArrayContent(inputBytes);
const string formDataKey = #"""file""";
const string formDataValue = #"""input.xml""";
var multipartFormDataContent = new MultipartFormDataContent()
{
{ byteArrayContent, formDataKey, formDataValue }
};
const string url = #"http://baseurl:port/my/resource/is/there.do?transformation=" + transformation;
var response = await httpClient.PostAsync(url, multipartFormDataContent);
return await response.Content.ReadAsStringAsync();
}
}
You really shouldn't be constructing an HttpClient every time the endpoint is called.
This is what I would do:
//create a service that caches HttpClient based on url
public interface IHttpClientService
{
IHttpClient GetClient(string baseHref);
void AddClient(HttpClient client, string baseHref);
}
//implement your interface
public class HttpClientService : IHttpClientService
{
private readonly ConcurrentDictionary<string, IHttpClient> _httpClients;
public HttpClientService()
{
_httpClients = new ConcurrentDictionary<string, IHttpClient>();
}
public void AddClient(HttpClient client, string baseHref)
{
_httpClients.
.AddOrUpdate(baseHref, client, (key, existingHttpClient) => existingHttpClient);
}
public IHttpClient GetClient(string baseHref)
{
if (_httpClients.TryGetValue(baseHref, out var client))
return client;
return null;
}
}
//register as singleton Startup.cs
services.AddSingleton<IHttpClientService, HttpClientService>();
//inject into Controller
[HttpGet]
public async Task<string> Get(string transformation = "xml")
{
const string url = #"http://baseurl:port/my/resource/is/there.do?transformation=" + transformation;
var httpClient = _httpService.GetClient(url);
if(httpClient == null)
{
httpClient = new HttpClient(url);
const string authScheme = #"Basic";
const string name = #"myUserName";
const string password = #"myPassword";
var authBytes = Encoding.ASCII.GetBytes($#"{name}:{password}");
var auth64BaseString = Convert.ToBase64String(authBytes);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authScheme, auth64BaseString);
const string fileName = #"input.xml";
var inputBytes = File.ReadAllBytes(fileName);
var byteArrayContent = new ByteArrayContent(inputBytes);
const string formDataKey = #"""file""";
const string formDataValue = #"""input.xml""";
var multipartFormDataContent = new MultipartFormDataContent()
{
{ byteArrayContent, formDataKey, formDataValue }
};
_httpClient.AddClient(httpClient, url);
}
else
{
//You can cache your MultipartFormDataContent in MemoryCache or same cache as HttpClient
//Get MultipartFormDataContent from cache and
}
var response = await httpClient.PostAsync(url, multipartFormDataContent);
return await response.Content.ReadAsStringAsync();
}

Setting Authorization Header of HttpClient

I have an HttpClient that I am using for a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from doing my OAuth request.
I saw some code for .NET that suggests the following,
httpClient.DefaultRequestHeaders.Authorization = new Credential(OAuth.token);
However the Credential class does that not exist in WinRT. Anyone have any ideas how to set the Authorization header?
So the way to do it is the following,
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "Your Oauth token");
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
$"{yourusername}:{yourpwd}")));
I look for a good way to deal with this issue and I am looking at the same question. Hopefully, this answer will be helping everyone who has the same problem likes me.
using (var client = new HttpClient())
{
var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetStringAsync(url);
// Parse JSON response.
....
}
reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices :( ), I put here a link towards the answer I made on a similar question :
https://stackoverflow.com/a/40707446/717372
Some sources on how to use HttpClient the right way:
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/
https://blogs.msdn.microsoft.com/alazarev/2017/12/29/disposable-finalizers-and-httpclient/
I suggest to you:
HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");
And then you can use it like that:
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}
In the case you want to send HttpClient request with Bearer Token, this code can be a good solution:
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(".....", Encoding.UTF8, "application/json"),
RequestUri = new Uri(".....")
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Your token");
var response = await _httpClient.SendAsync(requestMessage);
I was setting the bearer token
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
It was working in one endpoint, but not another. The issue was that I had lower case b on "bearer". After change now it works for both api's I'm hitting. Such an easy thing to miss if you aren't even considering it as one of the haystacks to look in for the needle.
Make sure to have "Bearer" - with capital.
Use Basic Authorization And Json Parameters.
using (HttpClient client = new HttpClient())
{
var request_json = "your json string";
var content = new StringContent(request_json, Encoding.UTF8, "application/json");
var authenticationBytes = Encoding.ASCII.GetBytes("YourUsername:YourPassword");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("YourURL", content);
var result_string = await result.Content.ReadAsStringAsync();
}
For anyone finding this old thread now (2021), please look at this documentation about HttpClientFactory which is injectable and will also re-run on each request avoiding expired tokens which will make it useful for bearer tokens, generated clients, pooling etc.
TL;DR: Use HttpClientFactory and a DelegatingHandler which will act as middleware on all outgoing requests with your configured client.
This is how I add my bearer for Azure Identity (managed by Azure) but you can get the token however you want of course;
using Microsoft.Azure.Services.AppAuthentication;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class BearerTokenHandler : DelegatingHandler
{
public BearerTokenHandler(AzureServiceTokenProvider tokenProvider, string resource)
{
TokenProvider = tokenProvider;
Resource = resource;
}
public AzureServiceTokenProvider TokenProvider { get; }
public string Resource { get; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("Authorization"))
{
// Fetch your token here
string token = await TokenProvider.GetAccessTokenAsync(Resource);
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
}
return await base.SendAsync(request, cancellationToken);
}
}
I configure my typed clients (generated with NSwag) like this in Startup;
var accessTokenProvider = new AzureServiceTokenProvider("<your-connection-string-for-access-token-provider>");
builder.Services.AddHttpClient<IOrdersClient, OrdersClient>().ConfigureHttpClient(async conf =>
{
conf.BaseAddress = new Uri("<your-api-base-url>");
}).AddHttpMessageHandler(() => new BearerTokenHandler(accessTokenProvider, "https://your-azure-tenant.onmicrosoft.com/api"));
Then you can inject your IOrdersClient wherever you like and all requests will have the bearer.
If you want to reuse the HttpClient, it is advised to not use the DefaultRequestHeaders as they are used to send with each request.
You could try this:
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent("...", Encoding.UTF8, "application/json"),
RequestUri = new Uri("...")
};
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
var response = await _httpClient.SendAsync(requestMessage);
To set basic authentication with C# HttpClient. The following code is working for me.
using (var client = new HttpClient())
{
var webUrl ="http://localhost/saleapi/api/";
var uri = "api/sales";
client.BaseAddress = new Uri(webUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.ConnectionClose = true;
//Set Basic Auth
var user = "username";
var password = "password";
var base64String =Convert.ToBase64String( Encoding.ASCII.GetBytes($"{user}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",base64String);
var result = await client.PostAsJsonAsync(uri, model);
return result;
}
This is how i have done it:
using (HttpClient httpClient = new HttpClient())
{
Dictionary<string, string> tokenDetails = null;
var messageDetails = new Message { Id = 4, Message1 = des };
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:3774/");
var login = new Dictionary<string, string>
{
{"grant_type", "password"},
{"username", "sa#role.com"},
{"password", "lopzwsx#23"},
};
var response = client.PostAsync("Token", new FormUrlEncodedContent(login)).Result;
if (response.IsSuccessStatusCode)
{
tokenDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
if (tokenDetails != null && tokenDetails.Any())
{
var tokenNo = tokenDetails.FirstOrDefault().Value;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tokenNo);
client.PostAsJsonAsync("api/menu", messageDetails)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
}
}
}
This you-tube video help me out a lot. Please check it out.
https://www.youtube.com/watch?v=qCwnU06NV5Q
6 Years later but adding this in case it helps someone.
https://www.codeproject.com/Tips/996401/Authenticate-WebAPIs-with-Basic-and-Windows-Authen
var authenticationBytes = Encoding.ASCII.GetBytes("<username>:<password>");
using (HttpClient confClient = new HttpClient())
{
confClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants.MediaType));
HttpResponseMessage message = confClient.GetAsync("<service URI>").Result;
if (message.IsSuccessStatusCode)
{
var inter = message.Content.ReadAsStringAsync();
List<string> result = JsonConvert.DeserializeObject<List<string>>(inter.Result);
}
}
UTF8 Option
request.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes(
$"{yourusername}:{yourpwd}")));
Using AuthenticationHeaderValue class of System.Net.Http assembly
public AuthenticationHeaderValue(
string scheme,
string parameter
)
we can set or update existing Authorization header for our httpclient like so:
httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);
BaseWebApi.cs
public abstract class BaseWebApi
{
//Inject HttpClient from Ninject
private readonly HttpClient _httpClient;
public BaseWebApi(HttpClient httpclient)
{
_httpClient = httpClient;
}
public async Task<TOut> PostAsync<TOut>(string method, object param, Dictionary<string, string> headers, HttpMethod httpMethod)
{
//Set url
HttpResponseMessage response;
using (var request = new HttpRequestMessage(httpMethod, url))
{
AddBody(param, request);
AddHeaders(request, headers);
response = await _httpClient.SendAsync(request, cancellationToken);
}
if(response.IsSuccessStatusCode)
{
return await response.Content.ReadAsAsync<TOut>();
}
//Exception handling
}
private void AddHeaders(HttpRequestMessage request, Dictionary<string, string> headers)
{
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (headers == null) return;
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
private static void AddBody(object param, HttpRequestMessage request)
{
if (param != null)
{
var content = JsonConvert.SerializeObject(param);
request.Content = new StringContent(content);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
}
SubWebApi.cs
public sealed class SubWebApi : BaseWebApi
{
public SubWebApi(HttpClient httpClient) : base(httpClient) {}
public async Task<StuffResponse> GetStuffAsync(int cvr)
{
var method = "get/stuff";
var request = new StuffRequest
{
query = "GiveMeStuff"
}
return await PostAsync<StuffResponse>(method, request, GetHeaders(), HttpMethod.Post);
}
private Dictionary<string, string> GetHeaders()
{
var headers = new Dictionary<string, string>();
var basicAuth = GetBasicAuth();
headers.Add("Authorization", basicAuth);
return headers;
}
private string GetBasicAuth()
{
var byteArray = Encoding.ASCII.GetBytes($"{SystemSettings.Username}:{SystemSettings.Password}");
var authString = Convert.ToBase64String(byteArray);
return $"Basic {authString}";
}
}
In net .core you can use with Identity Server 4
var client = new HttpClient();
client.SetBasicAuthentication(userName, password);
or
var client = new HttpClient();
client.SetBearerToken(token);
see https://github.com/IdentityModel/IdentityModel/blob/main/src/Client/Extensions/AuthorizationHeaderExtensions.cs
this could works, if you are receiving a json or an xml from the service and i think this can give you an idea about how the headers and the T type works too, if you use the function MakeXmlRequest(put results in xmldocumnet) and MakeJsonRequest(put the json in the class you wish that have the same structure that the json response) in the next way
/*-------------------------example of use-------------*/
MakeXmlRequest<XmlDocument>("your_uri",result=>your_xmlDocument_variable = result,error=>your_exception_Var = error);
MakeJsonRequest<classwhateveryouwant>("your_uri",result=>your_classwhateveryouwant_variable=result,error=>your_exception_Var=error)
/*-------------------------------------------------------------------------------*/
public class RestService
{
public void MakeXmlRequest<T>(string uri, Action<XmlDocument> successAction, Action<Exception> errorAction)
{
XmlDocument XMLResponse = new XmlDocument();
string wufooAPIKey = ""; /*or username as well*/
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
string documento = "";
MakeRequest(request,response=> documento = response,
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
XMLResponse.LoadXml(documento);
successAction(XMLResponse);
}
public void MakeJsonRequest<T>(string uri, Action<T> successAction, Action<Exception> errorAction)
{
string wufooAPIKey = "";
string password = "";
StringBuilder url = new StringBuilder();
url.Append(uri);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.ToString());
string authInfo = wufooAPIKey + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Timeout = 30000;
request.KeepAlive = false;
request.Headers["Authorization"] = "Basic " + authInfo;
// request.Accept = "application/json";
// request.Method = "GET";
MakeRequest(
request,
(response) =>
{
if (successAction != null)
{
T toReturn;
try
{
toReturn = Deserialize<T>(response);
}
catch (Exception ex)
{
errorAction(ex);
return;
}
successAction(toReturn);
}
},
(error) =>
{
if (errorAction != null)
{
errorAction(error);
}
}
);
}
private void MakeRequest(HttpWebRequest request, Action<string> successAction, Action<Exception> errorAction)
{
try{
using (var webResponse = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
var objText = reader.ReadToEnd();
successAction(objText);
}
}
}catch(HttpException ex){
errorAction(ex);
}
}
private T Deserialize<T>(string responseBody)
{
try
{
var toReturns = JsonConvert.DeserializeObject<T>(responseBody);
return toReturns;
}
catch (Exception ex)
{
string errores;
errores = ex.Message;
}
var toReturn = JsonConvert.DeserializeObject<T>(responseBody);
return toReturn;
}
}
}
It may be easier to use an existing library.
For example, the extension methods below are added with Identity Server 4
https://www.nuget.org/packages/IdentityModel/
public static void SetBasicAuthentication(this HttpClient client, string userName, string password);
//
// Summary:
// Sets a basic authentication header.
//
// Parameters:
// request:
// The HTTP request message.
//
// userName:
// Name of the user.
//
// password:
// The password.
public static void SetBasicAuthentication(this HttpRequestMessage request, string userName, string password);
//
// Summary:
// Sets a basic authentication header for RFC6749 client authentication.
//
// Parameters:
// client:
// The client.
//
// userName:
// Name of the user.
//
// password:
// The password.
public static void SetBasicAuthenticationOAuth(this HttpClient client, string userName, string password);
//
// Summary:
// Sets a basic authentication header for RFC6749 client authentication.
//
// Parameters:
// request:
// The HTTP request message.
//
// userName:
// Name of the user.
//
// password:
// The password.
public static void SetBasicAuthenticationOAuth(this HttpRequestMessage request, string userName, string password);
//
// Summary:
// Sets an authorization header with a bearer token.
//
// Parameters:
// client:
// The client.
//
// token:
// The token.
public static void SetBearerToken(this HttpClient client, string token);
//
// Summary:
// Sets an authorization header with a bearer token.
//
// Parameters:
// request:
// The HTTP request message.
//
// token:
// The token.
public static void SetBearerToken(this HttpRequestMessage request, string token);
//
// Summary:
// Sets an authorization header with a given scheme and value.
//
// Parameters:
// client:
// The client.
//
// scheme:
// The scheme.
//
// token:
// The token.
public static void SetToken(this HttpClient client, string scheme, string token);
//
// Summary:
// Sets an authorization header with a given scheme and value.
//
// Parameters:
// request:
// The HTTP request message.
//
// scheme:
// The scheme.
//
// token:
// The token.
public static void SetToken(this HttpRequestMessage request, string scheme, string token);
Firstly, I wouldn't use HttpClient directly. It's too easy to make mistakes - particularly in the area of headers. The DefaultHeadersCollection is not immutable and not thread-safe because other parts of the app can change the headers on you. It's best to set the headers when you make the call. If you are working with an abstraction, and that is recommended because the classes in this area are a bit of a mess, you would want to have a headers collection and put those on your HttpRequestMessage before you send it. You need to make sure you put the content headers on the content, and not the message.
Code Reference
foreach (var headerName in request.Headers.Names)
{
//"Content-Type"
if (string.Compare(headerName, HeadersExtensions.ContentTypeHeaderName, StringComparison.OrdinalIgnoreCase) == 0)
{
//Note: not sure why this is necessary...
//The HttpClient class seems to differentiate between content headers and request message headers, but this distinction doesn't exist in the real world...
//TODO: Other Content headers
httpContent?.Headers.Add(HeadersExtensions.ContentTypeHeaderName, request.Headers[headerName]);
}
else
{
httpRequestMessage.Headers.Add(headerName, request.Headers[headerName]);
}
}
Here is a data structure that you could use to send the request which includes the headers.
Code Reference
public interface IRequest
{
CancellationToken CancellationToken { get; }
string? CustomHttpRequestMethod { get; }
IHeadersCollection Headers { get; }
HttpRequestMethod HttpRequestMethod { get; }
AbsoluteUrl Uri { get; }
}
public interface IRequest<TBody> : IRequest
{
TBody? BodyData { get; }
}
And, a headers collection:
Code Reference
public sealed class HeadersCollection : IHeadersCollection
{
#region Fields
private readonly IDictionary<string, IEnumerable<string>> dictionary;
#endregion
#region Public Constructors
public HeadersCollection(IDictionary<string, IEnumerable<string>> dictionary) => this.dictionary = dictionary;
public HeadersCollection(string key, string value) : this(ImmutableDictionary.CreateRange(
new List<KeyValuePair<string, IEnumerable<string>>>
{
new(key, ImmutableList.Create(value))
}
))
{
}
#endregion Public Constructors
#region Public Properties
public static HeadersCollection Empty { get; } = new HeadersCollection(ImmutableDictionary.Create<string, IEnumerable<string>>());
public IEnumerable<string> Names => dictionary.Keys;
IEnumerable<string> IHeadersCollection.this[string name] => dictionary[name];
#endregion Public Properties
#region Public Methods
public bool Contains(string name) => dictionary.ContainsKey(name);
public IEnumerator<KeyValuePair<string, IEnumerable<string>>> GetEnumerator() => dictionary.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dictionary.GetEnumerator();
public override string ToString() => string.Join("\r\n", dictionary.Select(kvp => $"{kvp.Key}: {string.Join(", ", kvp.Value)}\r\n"));
#endregion
}
See all the working code and examples here.
You can too to use the follow exemple, that it use IHttpClientFactory:
readonly IHttpClientFactory _httpClientFactory;
public HTTPClientHelper(IHttpClientFactory httpClientFactory, string clientName = null)
{
this._httpClientFactory = httpClientFactory;
}
public Task<T> GetAsync(string url, string token) {
var client = _httpClientFactory.CreateClient(_clientName);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, token);
using (HttpResponseMessage response = await _client.GetAsync(url)){
......
}
}
I came across this old thread. The problem I had was that I know to use a static HttpClient, but my token needs refreshing every 59 minutes.
So I could have used HttpClientFactory, but because one of my projects was still in .NET 4.8, I created a class that inherited from HttpClient so I have similar code in all projects. A secret is needed to be able to get the token (I'm using identityserver4).
I then set that as a singleton in DI (I'm using Ninject here):
Bind<MyHttpClient>().ToMethod(c =>
{
var accessKey = ConfigurationManager.AppSettings["AccessKey"];
var client = new MyHttpClient(accessKey)
{
BaseAddress = new Uri(MyUrls.MyApiBaseUrl)
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
return client;
}).InSingletonScope();
Then the class itself - named after the API it is used to access:
public class MyHttpClient : BaseHttpClient
{
private static readonly HttpClient _authHttpClient = new HttpClient();
private string _secret;
public MyHttpClient(string secret)
{
_secret = secret;
}
/// <summary>
/// Add the token to each and every request, cached for 1 minute less than the token's lifetime
/// </summary>
/// <param name="request"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var cacheSeconds = 3600 - 60; // Default of 59 minutes
var token = CacheHelper<string>.Get("MyToken", cacheSeconds * 60, () =>
{
var authorityUrl = MyUrls.AuthServerUrl;
// discover endpoints from metadata
DiscoveryDocumentResponse disco;
disco = _authHttpClient.GetDiscoveryDocumentAsync(authorityUrl).Result;
if (disco.IsError)
{
throw new Exception("Error getting discovery document: " + disco.Error);
}
// request token
var tokenResponse = _authHttpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "myapp",
ClientSecret = _secret,
Scope = "myapi"
}).Result;
if (tokenResponse.IsError)
{
throw new Exception("Error getting token: " + tokenResponse.Error);
}
if (tokenResponse.ExpiresIn < cacheSeconds + 60)
{
throw new Exception($"Token expires in {tokenResponse.ExpiresIn}s, which is less than {cacheSeconds + 60}");
}
if (tokenResponse.ExpiresIn > cacheSeconds + 60)
{
Log.Warn().Message($"Token expiry in {tokenResponse.ExpiresIn}s, which is greater than {cacheSeconds}").Write();
}
return tokenResponse.AccessToken;
});
// THIS IS THE BIT - Assign this inside a SendAsync override and you are done!
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
return base.SendAsync(request, cancellationToken);
}
}
Finally just for completeness, my CacheHelper class looks like this:
public static class CacheHelper<T>
{
private static readonly object _locker = new object();
public static T Get(string cacheName, int cacheTimeoutSeconds, Func<T> func)
{
var obj = MemoryCache.Default.Get(cacheName, null);
if (obj != null) return (T)obj;
lock (_locker)
{
obj = MemoryCache.Default.Get(cacheName, null);
if (obj == null)
{
obj = func();
var cip = new CacheItemPolicy
{
AbsoluteExpiration = new DateTimeOffset(DateTime.UtcNow.AddSeconds(cacheTimeoutSeconds))
};
MemoryCache.Default.Set(cacheName, obj, cip);
}
}
return (T)obj;
}
}
Oauth Process flow is complex and there is always a room for one error or another.
My suggestion will be to always use the boilerplate code and a set of libraries for OAuth authentication flow.It will make your life easier.
Here is the link for the set of libraries.OAuth Libraries for .Net
If you are using Visual Studio IISExpress debug mode and connecting to the HTTP port rather than the HTTPS port you may find that the auth headers are being dropped.
Switch to the SLL connection and they will appear again.
unsure why, possibly the setup redirects the http traffic and that causes the auth to be removed.
This may help Setting the header:
WebClient client = new WebClient();
string authInfo = this.credentials.UserName + ":" + this.credentials.Password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
client.Headers["Authorization"] = "Basic " + authInfo;
static async Task<AccessToken> GetToken()
{
string clientId = "XXX";
string clientSecret = "YYY";
string credentials = String.Format("{0}:{1}", clientId, clientSecret);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
requestData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
var request = await client.PostAsync("https://accounts.spotify.com/api/token", requestBody);
var response = await request.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<AccessToken>(response);
}
}

Categories