I have a .NET Core Web Application and Web Api that I am calling from an IOS app (using Xamarin.ios). The web application is hosted in IIS on a private server. I am using MSAL single tenant to authenticate. That part seems to be working fine, as I can log in and get an access token.
The browser works fine, I can navigate to the WebApi no problem. However, when I try to make an http request to my Api, I get a 401 in my app. Here's the call:
string accessToken = await SecureStorage.GetAsync("AccessToken");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
HttpResponseMessage response = await _httpClient.GetAsync($"api/{uriSuffix}");
response.EnsureSuccessStatusCode();
string reply = await response.Content.ReadAsStringAsync();
return reply;
Debugging the server, I'm getting:
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException: 'IDX10511: Signature validation failed.
In the PII of the exception, it has my email, name, etc, leading me to believe that it successfully got my info from the token.
Any ideas?
I finally figured out the issue (or at least got it working). It had to do with the Audience. What is the Audience, you say? I couldn't tell you. But mine wasn't working because it's SINGLE-TENANT. Most tutorials I read used multi-tentant, which is handled differently.
Here's the change:
private IPublicClientApplication _pca;
readonly string[] Scopes =
{
"<tenant_id>/<api_permission>"
};
public AuthenticationHelper()
{
_pca = PublicClientApplicationBuilder.Create(<tenant_id>)
.WithIosKeychainSecurityGroup("com.microsoft.adalcache")
.WithRedirectUri("msauth.<bundle_id>://auth")
.WithAuthority("https://login.microsoftonline.com/<client_id>/v2.0")
.Build();
}
The important bit is the "Scopes" variable. Note, I prefix the api permission with "tenant_id\", where tenant_id is the guid of my tenant. Once I added that, it worked.
Related
Hello everyone my name is Taniguchi.
I've tried retrieving an entity from Dynamics 365 Finance and Operations and i did it on postman but now i having difficulties in asp.net core I was able to get the token but when i try to retrieve the entity the response gives me a html and this html leads me to the Dynamics 365 Finance and Operations Page.
My code:
`
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
const string environmentsUri = "https://trial-0z4qfj.sandbox.operations.dynamics.com/data/PartyContacts";
var response = httpClient.GetAsync(environmentsUri).Result;
var content = response.Content.ReadAsStringAsync().Result;
what am i doing wrong ? do i need to authenticate again ?
I suspect the Token you receive is not correct/complete.
I remember I faced the similar issue, I would request you to follow this blog post and try to receive Token as shown This shall help you solve your issue.
In addition I would recommend you use Organizaiton service with Webapi/Access Token. It will give you native library usage and you could query crm easily.
Try this blog for Orgservice
Seems like you are only using the parameter accessToken instead of the variable value. Depends on how you declared accessToken ofc. The rest seems fine.
Try:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token.accessToken);
I have registered an app in Azure. I can get access_token from oauth2/v2.0/token from password grant. I can also get refresh_token from oauth2/v2.0/token using refresh_token grant
But, How do I request a resource in Microsoft Azure using an access_token?
In short how can we use the generated access_token in azure?
When you would request anything on azure you have to pass your access
token as your request headerrequest.Headers.Authorization which is
Bearer token.
Here I am giving you an example how you could access azure resource using your access token.
//New Block For Accessing Data from Microsoft Graph Rest API
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://graph.microsoft.com/v1.0/users"));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
I am accessing Azure Active Directory User List using access token. I got this response
See the screenshot below:
Azure Resource API Access Sample :
As Per Gaurav Mantri's Recommendation I am also giving you another example how you could get azure resource group information. See below code snippet
//How You Would Request Microsft Resource Management API For Resources List
var azureSubcriptionId = "Your_Azure_Subcription_Id";
var resourceGroupName = "Your_Resource_Group_Name";
HttpClient _client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/resources?api-version=2019-10-01", azureSubcriptionId, resourceGroupName));
//Passing Token For this Request
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "Pass Your Token Here");
HttpResponseMessage response = await _client.SendAsync(request);
//Get User List From Response
dynamic objAzureResourceGroupList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
Also Tested on PostMan.
For more details you could refer Official Docs
Hope this would help you.
This process has been defined very clearly here: https://learn.microsoft.com/en-us/rest/api/azure. Especially look at the section titled Create the request which will tell you exactly what needs to be done.
I'm trying to upload a photo using the Picasa Web Albums Data API in C# and I'm using RestSharp to help me with the HTTP requests.
I have the client ID and the client secret, but I don't know how to put that on the http request to make the authentication.
I'm getting the error:
Modification only allowed with api authentication.
The StatusCode that is returning is Forbidden
Here is my code where is my user ID and is my album ID.
The method "Authenticantion()" returns a token that I already have.
[HttpPost]
public string PostImage(){
var restclient = new RestClient(BaseUrl);
RestRequest request = new RestRequest("https://picasaweb.google.com/data/feed/api/user/<userID>/albumid/<albumID>") {Method = Method.POST};
string imageBase64 = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAIUAyAMBEQACEQEDEQH/xAAcAAABBQEBAQAAAAAAAAAAAAAAAQIDBAUGBwj/xAA6EAABAwIDBgMFBgYDAQAAAAABAAIDBBEFITESE0FRYXEGIpEUMkJSgSMzYqGx0QdDgpLB4TVTchX/xAAaAQEAAwEBAQAAAAAAAAAAAAAAAQIDBQQG/8QAMREAAgIBAwMDAgMIAwAAAAAAAAECAxEEEjETIUEFMlEiYRRCkSMzUoGhsdHhNHHx/9oADAMBAAIRAxEA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QEzWNboEAtkAWQCoAQAgBACAEAIAQAgP//Z";
request.AddParameter("client_id", this._clientID);
request.AddParameter("client_secret", this._clientSecret);
request.AddParameter("grant_type", "client_credentials");
request.AddHeader("GData-Version", "3");
request.AddHeader("Content-Type", "image/jpeg");
request.AddHeader("accessToken", Authenticantion());
request.AddBody(#"Content-Length: 5951
Slug: banana.jpeg " + imageBase64);
var tResponse = restclient.Execute(request);
var responseJson = tResponse.Content;
var token = Authenticantion();
return responseJson;
}
The OAuth2 authentication normally happens inside a user flow, where the user makes the login with the user and allow (or not) some scopes to the app (e.g. access Picasa, read only for Google Drive).
You can check the complete flow through this link: OAuthPlayground. And get your own token at the end of the flow to use with your HTTP requests. One thing to take care is about refresh the tokens, inside the playground it's possible to set to never expire. But on the real world you would need to implement this refresh.
The Picasa API is a little outdated, I'd recommend you to use GoogleDrive instead, it's much more flexible and up to date.
GoogleDrive_API_Docs
It's also possible to make this flow via OAuth2_ Server to server, but I never tried before.
UPDATE: Figured this out. I DID need to add the authorization header as answered below but I also believe the issue for my particular use case is that the access token (which I verified through Postman) required more scopes to authenticate me fully, which makes sense since this API contains surveys that I am trying to access, which are also linked to a Google account. Once I added the extra scopes needed to access the surveys to the token request along with the authorization header code below I was able to connect successfully.
More info on adding scopes to C# code can be found here: http://www.oauthforaspnet.com/providers/google/
Hope this helps anyone running into similar issues. Thanks all!
I am trying to make a GET call to a Google API but it keeps responding with "Unauthorized" while I am logged in to Gmail. I've already implemented Google+ Sign-In in StartUp.Auth.cs and even saved the access token for later use.
So how do I get the HttpClient to authorize me?
I have an access token available but I do not know how to pass it in properly. I've seen examples with usernames and passwords, but I should not need to pass those parameters if I already have an access token? If anything, I should be able to have the user redirected to a login page instead if needed when I log out before running the solution.
What I am expecting when the project is run, is the result of the GET call to come back in the form of json but it always says I'm "Unauthorized" and I am probably missing 1 line of code somewhere...
Here is the code I am using:
using (HttpClient client = new HttpClient())
{
string _url = "https://www.googleapis.com/consumersurveys/v2/surveys?key={MY_API_KEY}";
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpResponseMessage response = client.GetAsync(_url).Result)
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var Content = content.ReadAsStringAsync();
ViewBag.GoogleResponse = Content.ToString();
}
}
else
{
// THIS IS ALWAYS UNAUTHORIZED!
ViewBag.GoogleResponse = response.StatusCode + " - " + response.ReasonPhrase;
}
}
}
Please help with ideas or suggestions. Thanks!
You need to pass the auth token in an Authorization Header:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Have you ever gotten an response for this api/survey? If you were unable to get a response from the API by hitting it with Postman, you may have issues in the way you are targeting the API. The error being returned there seems like you weren't including the token in your request header. Did you click the Authorization tab below the request URL to add the OAuth token to your header? (Keep in mind that the {} characters need to be URL encoded)
Also, when you are referencing MY_API_KEY, is that analagous to your surveyId?
I don't have a lot of experience here, but I have a couple of suggestions :
1) I agree with Pedro, you definitely need to include the Authorization Header in your request.
2) If your MY_API_KEY is in fact the survey ID, you may be providing an incorrect URL (GoogleAPIs documentation indicates that it should be < http://www.googleapis.com/consumer-surveys/v2/surveys/surveyId >
Recommendation (after moving your API key to a string var named MY_API_KEY) :
string _url = "https://www.googleapis.com/consumersurveys/v2/surveys/";
client.BaseAddress = new Uri(_url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ViewBag.GoogleAccessToken);
using (HttpResponseMessage response = client.GetAsync(MY_API_KEY).Result)
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var Content = content.ReadAsStringAsync();
ViewBag.GoogleResponse = Content.ToString();
}
}
Reference:
https://developers.google.com/consumer-surveys/v2/reference/
http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
After Twitter deprecated their Twitter API 1.0, I've tried several methods in order to get the 1.1 API working for my Windows 8 application. However, what you see below is basically what I've ended up with:
public List<UserTweet.User> jsonFromTwitter;
private async void fetchTweet()
{
var jsonTwitter = new Uri("http://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=stackoverflow&result_type=recent");
HttpClient client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, jsonTwitter);
var oAuthHeader = "OAuth oauth_consumer_key=\"XXXXX\", oauth_nonce=\"XXXXX\", oauth_signature=\"XXXXX\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1318622958\", oauth_token=\"XXXXX-XXXXXX\", oauth_version=\"1.0\"";
request.Headers.Add("Authorization", oAuthHeader);
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
jsonFromTwitter = JsonConvert.DeserializeObject<List<UserTweet.User>>(await client.GetStringAsync(responseString));
//listbox.ItemsSource = jsonFromTwitter;
}
However, this won't do much good, and it switches between mainly a couple of errors. One of them can be seen below, and the other one is "Could not authenticate user" or similar, basically there's something wrong with the headers as far as I've understood.
Anyone got any ideas on how to construct a working OAuth header for this? I'm clueless at the moment.
There's a lot more you need to do for the value assigned to the Authorization header - plain text won't work. The following pages in the Twitter OAuth documentation might help you get started in the right direction.
Twitter's Docs have a section on Authentication
Authorizing a Request
Creating Signatures