New to OData, I need to access SAP Odata Web Service that required Authentication and Token. Say I have the token hardcoded. How to add this token to Simple OData Client?
var settings = new Simple.OData.Client.ODataClientSettings();
settings.BaseUri = new Uri("https://..../UoM?$filter=wer eg '1000' &format=json");
settings.Credentials = new NetworkCredential("user1", "usrpwd");
var client = new ODataClient(settings);
Please kindly help me.
Update --
In this link : Simple Odata Client - How to add oAuth Token in each request header?
It didnot show how to add the hardcoded Token. For my problem, I need to add a given token and make a Odata Request. I check the Odata.org website, I dont seems to find any example for my case.
I have no experience on simple.Odata.client, Can some1 be kind enough to show me how.
Thanks
I believe you can use the ODataClientSettings.BeforeRequest action to alter the request before it is sent.
In the example below I set the Authorization header of the request to 'Bearer <Token>':
settings.BeforeRequest = req => {
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "Your_Token_Here");
};
Of course it is up to you to configure the request for you specific type of authentication.
The URL you use in your example is clearly wrong and not the OData URL for SAP.
You need the base URL for the "yourODataServiceRootURL" below and then add the relative path later in the ODataclient setting eg. "api/data/v9.1"
Instead of using the delegate method to intercept and add the Authorization header on every Http call, a clearer/cleaner solution is to instantiate the ODataClient with an HttpClient instance.
This also allows you to control the HttpClient lifecycle externally.
The code below is an extract of a .Net core app using an Azure AD OAuth2 token to connect to a Dynamics 365 OData Web API.
httpClient.BaseAddress = new Uri(yourODataServiceRootURL);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", yourBearerAccessToken);
//Use the httpClient we setup with the Bearer token header
var odataSettings = new ODataClientSettings(httpClient, new Uri("api/data/v9.1", UriKind.Relative));
var odataClient = new ODataClient(odataSettings);
Related
I am new to Xamarin Cross-Flatform technology (C#). I am developing one small application where I need to call the http url, get the json data, parse it and display it on the screen.
I am using System.Net.Http for achieving the http call.But request is not reaching to http url
Regards,
Amit Joshi
You can use RestSharp for making http calls.
It is very easy to use.
Code sample:
using RestSharp;
var client = new RestClient ("http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/");
var request = new RestRequest (String.Format ("{0}/allinfo", "198440"));
client.ExecuteAsync (request, response => {
Console.WriteLine (response.Content);
});
RestSharp Examples
Two things; first is I keep getting a 401 exception on the last line. I had thought that re-using the session would allow me to not only NOT have to resend the credentials but would also let me access the report by URL. It does neither...
Second, what do I do with the response once I have it to display it in the browser for the User?
This is what I have so far but I am unsure where to go with this from here....
var rs = new ReportExecutionService.ReportExecutionService();
rs.Credentials = new System.Net.NetworkCredential("UserID", "Pswd", "myDomain");
var execInfo = rs.LoadReport("/Nav Reports/OpenSalesOrderByCustomer", null);
var format = "HTML4";
string requestUri = string.Format(
#"https://reports.myServer.com/ReportServer/?{0}&rs:SessionId={1}&rs:Format={2}",
execInfo.ReportPath,
execInfo.ExecutionID,
format
);
WebRequest request = WebRequest.Create(requestUri);
request.UseDefaultCredentials = false;
request.Credentials = new System.Net.NetworkCredential("UserID", "Pswd", "myDomain");
var response = request.GetResponse();
For Background info -->
I am trying to setup Remote Report processing with SSRS on my asp.net web forms app. I would simply use the Report Viewer control but it's hideous looking and not acceptable to our user base. The URL Access returns a much better looking and formatted report and is acceptable but I have to pass Security Credentials. I would use SOAP API except it returns a non-styled html 'blob' and also removes the Toolbar functionality that we want to use.
So, I seem to be left with figuring out a way to use the SOAP API to authenticate a session and then somehow use that to use URL Access.
Just call the SOAP API, get the bytes, and return those bytes to the user with appropriate headers, content-type: application/pdf, content-disposition:attachment;filename=report.pdf. You don't need to do multiple calls to the report server.
I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.
Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.
The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).
Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?
the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.
HTH!
V.
The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know!
Thanks
V.
We have a Flex client and a server that is using the Spring/Blazeds project.
After the user logs in and is authenticated, the spring security layer sends a redirect to a new URL which is where our main application is located.
However, within the flex client, I'm currently using HTTPService for the initial request and I get the redirected page sent back to me in its entirety.
How can I just get the URL so that I can use navigatetourl to get where the app to go where it needs to?
Any help would greatly be appreciated. Thanks!
One solution would be to include a token inside a comment block on the returned page, for instance:
<!-- redirectPage="http://localhost/new-location" -->
then check for it's presence inside the HTTPService result handler. The token's value could then be used in your call to navigateToURL.
Another solution would be to examine the HTTP response headers and extract the value of the "Location" header using ActionScript. Consider using the AS3 HTTP Client lib.
From the examples page http://code.google.com/p/as3httpclientlib/wiki/Examples To determine the 'Location' header from the response:
var client:HttpClient = new HttpClient();
var uri:URI = new URI("http://localhost/j_security_check");
client.listener.onStatus = function(event:HttpStatusEvent):void {
var response:HttpResponse = event.response;
// Headers are case insensitive
var redirectLocation:String = response.header.getValue("Location");
// call navigateToURL with redirectLocation
// ...
};
// include username and password in the request
client.post(uri);
NOTE: AS3 HTTP Client depends on AS3 Core and AS3 Crypto libs.
You can also simply use the URLLoader class, no need for external code. One of the events it dispatches is HTTPStatusEvent.HTTP_RESPONSE_STATUS. Just plug into that and retrieve the redirected url:
urlLoader.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, onHTTPResponseStatus);
private function onHTTPResponseStatus(event:HTTPStatusEvent):void
{
var responseURL:String = event.responseURL;
}
I am (successfully) using this code right now, so if it doesn't work for some reason, let me know.
i like to preform simple facebook api call via http rest
but whiteout using facebook java/c++ pre made lib
plain http call
i already done the authorization part and i have the session id and all that .
i just like to see what i need to preform api call over http
thanks
Just use the Facebook Rest API to create your URLs and then send the response via POST
from http://www.exampledepot.com/egs/java.net/Post.html
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();