Apache HTTP Client Fluent - apache-httpclient-4.x

Hi I want to use Apache HTTP Client Fluent to create a request to download a file. I need to add Autorization Basic Auth to the request to pass in a username and password which I can't find a good example of how to do.
I can see a addHeader method but can't find good examples of how to construct it. Thanks!
So far the code i have is:
String auth = username + ":"+ token
byte[] encodedBytes = Base64.encodeBase64(auth.getBytes());
String encodedAuth = new String(encodedBytes)
URL downloadFileURL = new URL (urlbuild)
Executor executor = Executor.newInstance();
executor.execute(Request.Get(downloadFileURL.toURI())
.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth )
.connectTimeout(1000))
.saveContent(new File(mobileAppPath + System.getProperty("file.separator") + mobileApp.name));

the problem was due to Java trying to validate the SSL certificate i used Java code below to trust all hosts before executing the request.
https://www.javatips.net/api/java.security.cert.x509certificate

Related

how to pass http authentication headers in spring boot

I am working on customizing my spring boot authorization server. After login using username and password from the html page I have created I need to redirect back to /oauth/token endpoint ,in order to get the access token .
It is working fine while using postman. But when I give defaultsuccessurl as /ouath/token it shows me a default login page to enter username and password which the basic auth username and password from postman.
so, in order to get the access token from front end I need to add basic auth details as http header. I don't know where to add HTTP header and how to use that to get the access token after successful login using front end.
Any help appreciated
There are multiple ways to do it. One way is: along with html, you can use Javascript to set HttpHeaders and send the request. Below a sample code snippet (not complete though)
var user = "user1"; //ideally this should come from Input field in html page
var password = "MySecret";//ideally this should come from password field in html page
// var authorizationBasic = $.base64.btoa(user + ':' + password);
var authorizationBasic = window.btoa(user + ':' + password);
var request = new XMLHttpRequest();
request.open('POST', oAuth.AuthorizationServer, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("<requestURL>");

LoginRadius Validating access token .net core

I am trying to validate my access token (not JWT) with LoginRadius, I can do the login but after when I call my API I always get unauthorized or different errors according to my Authentication configuration, I am using like this. I believe the authority url is not correct but I couldn't find any other
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect("login-radius", options => {
// Set the authority to your Auth0 domain
options.Authority = $"https://api.loginradius.com/identity/v2/auth/";
// Configure the Auth0 Client ID and Client Secret
options.ClientId = Configuration["ClientId"];
options.ClientSecret = Configuration["ClientSecret"];
// Set response type to code
options.ResponseType = OpenIdConnectResponseType.Code;
options.Scope.Clear();
options.Scope.Add("openid");
options.CallbackPath = new PathString("/callback");
options.ClaimsIssuer = "loginradius";
// Saves tokens to the AuthenticationProperties
options.SaveTokens = true;
});
I believe you are trying to setup OIDC, and to configure it, please refer to the LoginRadius docs on OIDC, as it needs few things that need to be configured in the Admin Console and the correct authority URL: https://www.loginradius.com/docs/single-sign-on/tutorial/federated-sso/openid-connect/openid-connect-overview/#otheropenidfunctionality6
Please refer to the OIDC discovery endpoint, which provides a client with configuration details about the OpenID Connect metadata of the Loginradius App.
URL Format: https://cloud-api.loginradius.com/sso/oidc/v2/{sitename}/{oidcappname}/.well-known/openid-configuration
My account didn't have access to few features

WinRT use HttpClient to call Web API based URL with token

We are building a WinRT app which gets data from server which is Web API based & so it gives data in json and/or XML format.
When app user logs in for the first time using his credentials(username,password), the response that comes from server is a success bit & a TOKEN, which should be used in successive URL requests.
I am using httpclient for sending requests
using (HttpClient httpClient1 = new HttpClient())
{
string url = "http://example.com/abc/api/process1/GetLatestdata/10962f61-4865-4e7a-a121-3fdd968824b5?employeeid=6";
//The string 10962f61-4865-4e7a-a121-3fdd968824b5 is the token sent by the server
var response = await httpClient1.GetAsync(new Uri(url));
string content = await response.Content.ReadAsStringAsync();
}
Now the response that i get is with status code 401 "unauthorised".
And the xml i get in response is "Unauthorised User".
Is there anything i need to change in appManifest??
I've checked this, but cant we use httpclient without credentials??
Your Capabilities are enough. You don't even need Internet (Client) because it's included in Internet (Client & Server).
You do not have credentials for WinRT HttpClient, in your linked post they referr to System.Net.Http.HttpClientHandler.
Maybe you can use the HttpBaseProtocolFilter to add the credentials?
using (var httpFilter = new HttpBaseProtocolFilter())
{
using (var httpClient = new HttpClient(httpFilter))
{
httpFilter.ServerCredential...
}
}
I don't know your security mechanism, I'm using a HttpClient and my session-key is in a cookie. But I think your client code looks fine.

Bitcoind JSON-RPC : Java Jersey Client : Unexpected end of file from server Error

I am very new to bitcoin and this is my first experiment with bitcoind.
We have been trying to develop an Java based application on BTC using bitcoind (using testnet). We are using simple HTTP Post using Jersey client with basic authentication like given below. We already have jersey client as part of project dependencies. We are running on Mac OS. The bitcoind and java client are hosted in the same system.
Client client = Client.create();
String url = "http://"+username+':'+password+"#localhost:18333";
//String url = "http://localhost:18333";
System.out.println("URL is : "+url);
WebResource webResource = client.resource(url);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication (username, password.toCharArray());
}
});
String input = "{\"method\":\"getblockcount\",\"params\":[],\"id\":\"1\"}";
ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);
When we execute this, we are getting
Caused by: java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:772)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:769)
From the exception what I understand is, there are some server side errors but i am not able to see errors in the log files. The degug.log does not give any details.
The entries in the bitcoin.conf file is as follows:
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
Also I tried integrating with bitcoind using json-rpc client as well which resulted in the same error.
Really appreciate any help in resolving this error. Thank you in advance. Let me know if you need any further details.
Regards,
Manjunath
====== EDIT ======
When I inspect the request and response, its giving "Remote server closed the connection before sending response header" error as part of HTTP failure scenario. Following is the request data content :
URL : http://192.168.2.111:18333/
Request Data:
{
"method": "getblockcount",
"params": [],
"id": "1"
}
Please help me in understanding where the mistake is.
================ EDIT =================
Added below entries to bitcoin.conf to allow connections from client. But still facing the same error:
rpcallowip=192.168.2.111
rpcallowip=127.0.0.1
Regards,
Manjunath
After all tweaking, I am able to get it working properly. For the benefit of others, here is the Java Code for making JSON-RPC calls to bitcoind (Using Jersey Client):
bitcoin.conf entries :
rpcuser=bitcoinrpc
rpcpassword=5UKQTzWTf7EEJnkShZhr9tbjpDVNmLMgQkFfWsnZhLey
testnet=1
server=1
#txindex=1
rpcallowip=192.168.2.*
rpcallowip=127.0.0.1
rpcport=8999
#rpctimeout=60000
Make sure you change the port number and dont forget to provide rpcallowip entry pointing to respective IP address.
Client Code:
DefaultClientConfig config = new DefaultClientConfig();
config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,
Boolean.TRUE);
Client client = Client.create(config);
client.addFilter(new HTTPBasicAuthFilter(username, password));
WebResource webResource = client.resource(url);
String input = "{\"id\":\"jsonrpc\",\"method\":\"listaccounts\",\"params\":[]}";
ClientResponse response = webResource.accept("application/json").type("application/json")
.post(ClientResponse.class, input);
Thats it. Your good to start with bitcoind integration.
Regards,
Manjunath

Downloading Secondary Domain User Documents Google Document List Api 2-Legged Oauth

First post so sorry for any formatting issues.
I am trying to download a secondary domain user's documents via oauth and receiving a com.google.gdata.util.AuthenticationException: Unauthorized error. I am able to pull the users document using a feed call similar to this :
String docUrl = "https://docs.google.com/feeds/" + DOC_OWNER + "/private/full/" + DOC_ID + "?xoauth_requestor_id="+ PRIMARY_ADMIN_EMAIL
DocumentListEntry googleDoc = docServ.getEntry(new URL(docUrl), DocumentListEntry.class);
String exportUrl = ((MediaContent) googleDoc.getContent()).getUri().toString();
exportString = ((MediaContent) googleDoc.getContent()).getUri().split("&xoauth_requestor_id=")[0];
exportString + EXPORT_TYPE // add export type
but then when trying to download the document such as :
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
String mcUrl = mc.getUri() + "&xoauth_requestor_id=" + DOC_OWNER;
MediaSource ms = docServ.getMedia(mc);
This throws the authentication exception. I have tried swapping out the requestor id for the primary domain admin with no success. I have also tried using user creds for the primary domain admin and that throws a service forbidden exception. Anyone have any suggestions?
By default, the domain's OAuth key/secret don't have access to secondary domains. You need to manually enter the key (primary domain) and the Docs API scopes:
https://docs.google.com/feeds/,https://docs.googleusercontent.com/,https://spreadsheets.google.com/feeds/
at:
https://www.google.com/a/cpanel/YOUR-DOMAIN-HERE/ManageOauthClients
for it to work with secondary domain accounts.