I am currently using a Get Request with proxy information:
String result1 = Request.Get("_http://somehost/")
.version(HttpVersion.HTTP_1_1)
.connectTimeout(1000)
.socketTimeout(1000)
.viaProxy(new HttpHost("myproxy", 8080))
.execute().returnContent().asString();
The result is a "Proxy Authentication Required" error. I believe a username and password is required from the server making the request? If so, how do I add that detail? I have never used the Fluent API before.
Here is an example using the Fluent API. The executor can be used to specify credentials for the proxy.
HttpHost proxyHost = new HttpHost("myproxy", 8080);
Executor executor = Executor.newInstance()
.auth(proxyHost, "username", "password");
String result1 = executor.execute(Request.Get("_http://somehost/")
.viaProxy(proxyHost))
.returnContent()
.asString();
You need a CredentialsProvider.
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(username, password));
final HttpPost httppost = new HttpPost(uri);
httppost.setConfig(RequestConfig.custom().setProxy(proxy).build());
String line = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build() .execute(httppost).getStatusLine());
Also, there was a bug in 4.3.1 that impacted authentication. It is fixed in 4.3.2.
https://issues.apache.org/jira/browse/HTTPCLIENT-1435
Executor executor = Executor.newInstance()
.auth(new HttpHost("myproxy", 8080), "username", "password")
.authPreemptive(new HttpHost("myproxy", 8080));
Response response = executor.execute(<your reques>);
Related
Given I have the following info from Azure app registration:
Application (client) ID,
Client secret,
Directory (tenant) ID,
Object ID
Is there a way to check it's a valid credential programmatically (like using curl etc but not powershell)?
If you meant to check client secret validity or even the properties of that app ,then please check if the below c# code can be worked around .We can try to query the application and see expiry date of secret. Please grant the app with Directory.Read.All ,Application.Read.All permission to this API for using client credentials flow.
var graphResourceId = "https://graph.microsoft.com";
var applicationId= "";
var ObjectId = "";
var clientsecret = "";
var clientCredential = new ClientCredential(applicationId,secret);
var tenantId = "xxx.onmicrosoft.com";
AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}");
//get accesstoken
var accessToken = authContext.AcquireTokenAsync(graphResourceId, clientCredential).Result.AccessToken;
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
var app = activeDirectoryClient.Applications.GetByObjectId(appObjectId).ExecuteAsync().Result;
foreach (var passwordCredential in app.PasswordCredentials)
{
Console.WriteLine($"KeyID:{passwordCredential.KeyId}\r\nEndDate:{passwordCredential.EndDate}\r\n");
}
If you want , you can even request token using curl this way and validate using post man or by checking token in https://jwt.io .
Reference: check client secret expiry using C#
I am trying to call the Microsoft Graph API to create a domain. Unfortunately when I go to make the call, I receive an error stating that the "JSON Payload is empty".
Here is the call I am making:
GraphServiceClient _graphServiceClient =
new GraphServiceClient(new GraphAuthenticationHelper(NetOrgDomain));
HttpRequestMessage httpRequestMessage =
new HttpRequestMessage(httpMethod, requestUri);
string content = "{\"id\": \"sampleDomainAdd.info\"}";
var json = JsonConvert.SerializeObject(content);
var jsonContent = new StringContent(json, Encoding.UTF8, "application/json");
httpRequestMessage.Content = jsonContent;
HttpResponseMessage response =
await _graphServiceClient.HttpProvider.SendAsync(httpRequestMessage);
You've got an mix of Graph SDK and direct HTTP calls going on here. When using the Microsoft Graph .NET Client Library, you should be using the objects it provides rather than attempting to roll your own.
It also greatly simplifies your code:
var domain = await graphClient.Domains.Request().AddAsync(new Domain
{
Id = "sampleDomainAdd.info"
});
As an aside, the error you're getting currently is due to you're sending the data without the content-type being set to application/json in your HTTP request.
With Solr 6.3.0, in cloud mode, and 3 external zookeepers as cluster, and use solrJ as client.
A: Without authentication
Before enabling authentication, I use following code to add/update document:
CloudSolrClient client = cloudClientBuilder.build();
UpdateResponse resp = client.add(doc, 5000);
client.commit();
client.close();
return resp;
It works well, the new document is in searching result immediately.
B: With authentication enabled
Then I enabled basic authentication plugin and rule-based authorization plugin (and SSL if that matters).
In order to set credential information, the code is refactored as following:
// create request,
UpdateRequest req = new UpdateRequest();
// add doc to request,
req.add(doc, 5000);
// set credential,
req.setBasicAuthCredentials(user, password);
// create client,
CloudSolrClient client = cloudClientBuilder.build();
client.setDefaultCollection(ConfigUtil.getProp(ConfigUtil.KEY_SOLR_CORE));
// do request & get response,
UpdateResponse resp = req.process(client);
client.commit();
client.close();
Then it will get error similar as this:
Error 401 require authentication, require authentication.
When debugging, the error occurs at line client.commit();.
Try with curl
I use curl to make an update:
curl -k --user solr:password "https://localhost:8983/solr/corexxx/update?wt=json&indent=true&commit=true" -d '[{"id":"20041", "name":"xxx 41", "location":"xxx", "description":"xxx"}]'
It committed successfully ! And, the updates are visible in searching result immediately.
My guess
Since curl works well, I guess solr cloud itself works fine.
Thus the issue is due to the code from B which is based on SolrJ.
Questions:
Why code B get HTTP 401 error? How can I fix it?
Could I use code from A, and still able to provide credential information,if yes, then how?
Thanks.
You should change client.commit() for req.commit(client, ConfigUtil.getProp(ConfigUtil.KEY_SOLR_CORE)), the credentials are setted in the UpdateRequest.
It worked like this:
SolrClient client = new HttpSolrClient.Builder(urlString).build();
UpdateRequest up = new UpdateRequest();
up.setBasicAuthCredentials(user, pass);
up.add(doc1);
up.process(client, core);
up.commit(client, core);
client.close();
I have added my web application into onelogin using SAML Test Connector.
In Configuration tab I have given the following values
Recipient : http://localhost:8080/em/live/pages/samlAuth/
ACS(Consumer) URL Validator* : ^
ACS (Consumer) URL* :http://localhost:8080/ws_em/rest/accounts/consume-saml
Login URL : http://localhost:8080/ws_em/rest/accounts/produce-saml
Where http://localhost:8080/ws_em/rest/accounts/produce-saml creates an SAML Request by taking IssuerUrl, SAML EndPoint Copied From Onelogin SSO Tab and ACS url as http://localhost:8080/ws_em/rest/accounts/consume-saml.
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/produce-saml")
public com.virima.em.core.Response SAMLAuthentication(){
com.Response resp = new com.Response();
AppSettings appSettings = new AppSettings();
appSettings.setAssertionConsumerServiceUrl(ACSUrl);
appSettings.setIssuer(IssuerUrl));
AccountSettings accSettings = new AccountSettings();
accSettings.setIdpSsoTargetUrl(IdpSsoTargetUrl);
AuthRequest authReq = new AuthRequest(appSettings,accSettings);
Map<String, String[]> parameters = request.getParameterMap();
String relayState = null;
for(String parameter : parameters.keySet()) {
if(parameter.equalsIgnoreCase("relaystate")) {
String[] values = parameters.get(parameter);
relayState = values[0];
}
}
String reqString = authReq.getSSOurl(relayState);
response.sendRedirect(reqString);
resp.setResponse(reqString);
return resp;
}
http://localhost:8080/ws_em/rest/accounts/consume-saml calls is supposed to take my SAML request and do the authentication . Here I am using the certificate generated in Onelogin SSO Tab
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/consume-saml")
public com.onelogin.saml.Response SAMLAuthenticationResponse(){
com.onelogin.saml.Response samlResponse = null;
String certificateS ="c"; //Certificate downloaded from Onelogin SSO Tab
AccountSettings accountSettings = new AccountSettings();
accountSettings.setCertificate(certificateS);
samlResponse = new com.onelogin.saml.Response(accountSettings,request.getParameter("SAMLResponse"),request.getRequestURL().toString());
if (samlResponse.isValid()) {
// the signature of the SAML Response is valid. The source is trusted
java.io.PrintWriter writer = response.getWriter();
writer.write("OK!");
String nameId = samlResponse.getNameId();
writer.write(nameId);
writer.flush();
} else {
// the signature of the SAML Response is not valid
java.io.PrintWriter writer = response.getWriter();
writer.write("Failed\n");
writer.write(samlResponse.getError());
writer.flush();
}
return samlResponse;
}
I am getting this error
Federation Exception: Malformed URL. Please contact your
administrator.
It doesn't seem to come inside the ACS url I have inside my app.
Is there any mistakes in my configuration ? Or is there a better way to do this ?
ACS is Assertion Consumer Service, is the endpoint that process at the SP the SAMLResponse sent by the Identity Provider, so the http://localhost:8080/ws_em/rest/accounts/consume-saml process and validate the SAMLResponse.
Do you have verbose trace error? Malformed URL must be that the code is trying to build a URL var with a non URL string.
BTW, You are using the java-saml toolkit, but the 1.0 version instead the recommended 2.0.
I highly recommend you to use the 2.0 and before work on your integration, try to run the app example
I'm trying to authenticate to google app engine programmatically.
I've tried the code sample from the "gae-app-manager" project but it fails:
tmp>java -jar net.sf.gae-app-manager-0.0.1-jar-with-dependencies.jar myaccount#gmail.com mypassword appname
Exception in thread "main" java.lang.Exception: Did not find ACSID cookie
at net.sf.gaeappmanager.google.LogonHelper.loginToGoogleAppEngine(LogonHelper.java:85)
at net.sf.gaeappmanager.google.appengine.Manager.retrieveAppQuotaDetails(Manager.java:34)
at net.sf.gaeappmanager.google.appengine.Main.main(Main.java:55)
Any idea? I'm able to get the token, but there are no cookies.
The code (taken from the gae-app-manager project - http://gae-app-manager.git.sourceforge.net/git/gitweb.cgi?p=gae-app-manager/gae-app-manager;a=blob;f=src/main/java/net/sf/gaeappmanager/google/LogonHelper.java;h=8e09a6d7f864c29b10847ac7fd2eeab2d3e561e6;hb=HEAD):
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE"));
nvps.add(new BasicNameValuePair("Email", userid));
nvps.add(new BasicNameValuePair("Passwd", password));
nvps.add(new BasicNameValuePair("service", "ah"));
nvps.add(new BasicNameValuePair("source", source));
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Error obtaining ACSID");
}
String authToken = getAuthToken(response.getEntity().getContent());
post.abort();
HttpGet get = new HttpGet(
"https://appengine.google.com/_ah/login?auth=" + authToken);
response = client.execute(get);
for (Cookie cookie : client.getCookieStore().getCookies()) {
if (cookie.getName().startsWith("ACSID")) {
return cookie.getValue();
}
}
get.abort();
throw new Exception("Did not find ACSID cookie");
Thanks,
Li
Have you considered using the OAuth support instead of trying to log in as a web client would? Every App Engine app can act as an OAuth provider with very little work required on the server side to set it up.
To solve the problem use "SACSID" instead of "ACSID"