I am trying to make a httprequest to a web that is authenticated with ADFS of a private company.
I am able to login and get the token of my App. I am sure I am doing it correct due to I can get the contacts of my O365.After getting the token I try to make a request to the web. As I already have the token, I try to include it in the header of the request. The answer that I receive from the web is always the html with the login web not the result that I am requesting. As additional information I have added a "Connected Service" O365 API from VisualStudio.
This is my code:
public static async Task<string> GetAnswer(string wwweb)
{
var token = await GetAccessToken();
using (var client = new HttpClient())
{
var url = wwweb;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
//client.DefaultRequestHeaders.ProxyAuthorization= new AuthenticationHeaderValue("Bearer", token);
// client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetStringAsync(url);
return response;
}
}
I have tried with the 3 lines ( 2 commented and one not) without success, always giving back company's login web. Am I doing something wrong?
Thanks
Related
I have one method for login as per below :
public async Task<ActionResult> Index(LoginModel loginModel)
{
string url = "API_URL";
var response = await client.PostAsJsonAsync(url, loginModel);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
var jsonData = JObject.Parse(result);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + jsonData["accessToken"]);
return RedirectToAction("PostLogin");
}
else
{
ModelState.AddModelError("", "These credentials does not work. Hmm..");
}
return View(loginModel);
}
Now in this if user successfully login then I am getting token and also I am setting that in header. Now after that I am redirecting user to PostLogin method.
But in that method I am not able to access that token. Below is code for that.
public async Task<ActionResult> PostLogin()
{
var accessToken = await HttpContext.GetTokenAsync("accessToken"); // Here I can't see token. and getting value as per below.
return View();
}
Even I am getting this error as per below :
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultAuthenticateScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions).
You have commented that at start of controller you have HttpClient client = new HttpClient(); which is new instance of HttpClient
So in your function you are setting that objects authorization using this line: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + jsonData["accessToken"]);.
After that you are getting users authorization from current HttpContext which is sent each time user visits some link and it does not have anything with your client object you just set authorization to.
Since you are redirecting you must change current HttpContext authorization header since it will be carried to redirected request. Do it by changing HttpContext.Request.Headers["Authorization"]. Problem is that it will only last that request so you need to give token back to client so he sends it in header each time he makes request.
I am writing a code that directs users to an external API provider webpage where they will enter their login details and then return the code the end of the redirect url.
The code below does not work. It does not even redirect to the authorisation url.
I'm using Oauth2.0 and doing this in c# asp.netcore. Thank you in advance
public async Task<IActionResult> GetCode()
{
vurl = Provider.GetUrl();
//redirect user to url
return Redirect(vurl);
//read and extract code from url
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:8000/");
var client = _clientFactory.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.hmrc.1.0+json"));
var response = await client.SendAsync(request);
string resp = await response.Content.ReadAsStringAsync();
}
PS: the question has been edited with updated code
I have two web APIs applications developed in .Net core. I need to import Json data from the second application to the first. However,I have a security issue. I need to secure the access to the external API. How should I securely manage the connection between these two APIs.
For example, I need to secure the access to the URL in the code bellow => securely access to the covid API without another authentication.
PS: I'm using JWT token authentication in both applications
Best regards.
using (var client = new HttpClient())
{
string url = string.Format("https://covid19.mathdro.id/api");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}
If both APIs are protected by the same accessToken, then you can read the authorization header from the first request and pass it to the second request.
Something like this to read the header:
var authHeader = context.Request.Headers.Get("Authorization");
You should end up with authHeader equal to "Bearer ey...(a bunch of base64)"
Then add the auth header to the client:
var request = new HttpRequestMessage() {
RequestUri = new Uri("http://https://covid19.mathdro.id/api"),
Method = HttpMethod.Get,
};
...
request.Headers.Authorization.Add(new AuthenticationHeaderValue(authHeader));
var task = client.SendAsync(request)
I'm trying to access/call methods in a REST API with a token from c#/.net- but I can't get any response back. I have googlet a lot - but without any success :-( I am new to call methods via a REST API.
I have an endpoint and a token which I need to use for communicating with a REST API. And I need to GET, POST, PUT and DELETE data on the server via those methods
The output from the API is in JSON format.
Maybe it is simple - but I don't know howto do it.
Any help is appreciated.
I have tried the following solution - but with no success :-(
private static async void DoIt()
{
using (var stringContent = new StringContent("{ \"firstName\": \"Andy\" }", System.Text.Encoding.UTF8, "application/json"))
using (var client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
// 1. Consume the POST command
var response = await client.PostAsync(endpoint, stringContent);
var result = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from POST command: " + result);
// 2. Consume the GET command
response = await client.GetAsync(endpoint);
if (response.IsSuccessStatusCode)
{
var id = await response.Content.ReadAsStringAsync();
//Console.WriteLine("Result from GET command: " + result);
}
}
catch (Exception ex)
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine(ex.Message);
//Console.ResetColor();
}
}
}
In your code you initialize AuthenticationHeaderValue with "Basic", which means Basic authentication based on username and password. If you have a token, you do it with:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ACCESS_TOKEN);
replace ACCESS_TOKEN with the token you have.
This is the most probable solution, but I can only guess here, as I don't know the API you're trying to access. If it still doesn't work, try ommiting "Bearer".
Reference
I am running into an odd issue with trying to access a thumbnail image stored on O365 video via C#. I can access the REST API with no issue at all, I just add the Authentication: Bearer <token> to the header and I am off an running. The trouble is with a basic image URL that I get back from a specific video.
https://<mytenant>.sharepoint.com/portals/Channel1/pVid/myvideo.mp4.PNG?VideoPreview=1
When I access that URL from a browser it works 100% of the time. When I try to access it via the httpclient object, I am getting a 401 Unauthorized error.
The best I can figure is that the authorization header token is not being honored when accessing a basic URL. Which makes me thing that I need something else like a cookie? However I cannot seem to figure out which one. Looking for any advice :)
Pass credentials instead and yes you need an authentication cookie. Here is a sample:
private static async Task<string>getWebTitle(string webUrl)
{
//Creating Password
const string PWD = "softjam.1";
const string USER = "bubu#zsis376.onmicrosoft.com";
const string RESTURL = "{0}/_api/web?$select=Title";
//Creating Credentials
var passWord = new SecureString();
foreach (var c in PWD) passWord.AppendChar(c);
var credential = new SharePointOnlineCredentials(USER, passWord);
//Creating Handler to allows the client to use credentials and cookie
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Getting authentication cookies
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoking REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
string jsonData = await response.Content.ReadAsStringAsync();
return jsonData;
}
}
}