Solr Change CommonsHttpSolrServer To HttpSolrServer - solr

For Basic Authentication in solr 3.5 I am using the following code,
String url = "http://192.168.192.11:8080/solr/FormResponses";
CommonsHttpSolrServer server = new CommonsHttpSolrServer( url );
String username = "user";
String password = "user123";
Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
server.getHttpClient().getState().setCredentials(AuthScope.ANY, defaultcreds);
server.getHttpClient().getParams().setAuthenticationPreemptive(true);
In solr 4.0 CommonsHttpSolrServer is not available, so I want to replace it with
HttpSolrServer. Can anyone help me to fix this?

Change the code as follows :
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
String url = "http://192.168.192.11:8080/solr/FormResponses";
HttpSolrServer server = new HttpSolrServer( url );
DefaultHttpClient client = (DefaultHttpClient) server.getHttpClient();
UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials("user", "user123");
client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
For server.getHttpClient().getParams().setAuthenticationPreemptive(true) in HttpClient 4 you can use the solution described here.

Finally I find the answer my self,
String url = "http://192.168.192.11:8080/solr/FormResponses";
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials("user", "user123"));
SolrServer solrServer = new HttpSolrServer(url, httpclient);

You need to add the JAR solr-solrj-4.0.0.jar for HttpClientUtil .
Then use below code :
HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/"+url);
HttpClientUtil.setBasicAuth((DefaultHttpClient) solrServer.getHttpClient(),
"USERNAME", "PASSWORD");
That worked for me.

This is the only way that works for me:
String url = "192.168.192.11:8080/solr/FormResponses";
String username = "user";
String password = "user123";
HttpSolrServer server = new HttpSolrServer("http://" + username + ":" + password + "#" + url);

Related

What is the source code to connect an SQL server using kerberos authentication via JDBC?

Can any one help me in jdbc connection code for kerberos authentication ? I wrote the below code and I am not sure if miss anything important.
String filePath = System.getProperty("user.dir")+File.separator+"KerberosConfDir";
System.out.println(filePath);
String connectionUrl = "jdbc:sqlserver://mymachine;databaseName=master;integratedSecurity=true;authenticationScheme=JavaKerberos";
Properties connProperties = new Properties();
//connProperties.put("serverSpn","MSSQLSvc/mymachine.mydomain.com:1433");
System.out.println("connectionUrl : "+connectionUrl);
Connection con = null;
System.setProperty("sun.security.krb5.debug", "true");
System.setProperty("java.security.auth.login.config", filePath+File.separator+"SQLJDBCDriver.config");
System.setProperty("java.security.krb5.conf", filePath+File.separator+"krb5.ini");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Loading the Driver....");
con = DriverManager.getConnection(connectionUrl);
System.out.println("Establishing the connection....");
DatabaseMetaData dbmd = con.getMetaData();
System.out.println("dbmd:driver version = " + dbmd.getDriverVersion());
System.out.println("dbmd:driver name = " + dbmd.getDriverName());
System.out.println("db name = " + dbmd.getDatabaseProductName());
System.out.println("db ver = " + dbmd.getDatabaseProductVersion());
}
catch (Exception e) {
e.printStackTrace();
}

Validate SAML Response

I have a SAML response and few other data. Based on this, I need to validate if the response has been tampered or not. How can I do that?
What all I have?
SAML Response with Signed Message & Assertion
IdP EntityId
SP EntityId
SP ACS Endpoint
Target URL
Certificate of the IdP in X509 format.
Language needed: JAVA
Got a solution. If anyone is loking for it.
try {
InputStream is = new FileInputStream("<CERTIFICATE FILE>");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
X509Certificate x509Certificate = (X509Certificate) cert;
PublicKey pk = x509Certificate.getPublicKey();
BasicX509Credential publicCredential = new BasicX509Credential();
publicCredential.setPublicKey(pk);
SignatureValidator signatureValidator = new SignatureValidator(publicCredential);
SignableSAMLObject signableSAMLObject = (SignableSAMLObject) <XML OBJECT>;
Signature signature = signableSAMLObject.getSignature();
signatureValidator.validate(signature);
}catch(Exception ex){
// fail this.
}
XML Object can be obtained from SAML Message using marshaller in following way:
String encodedMessage = request.getParameter(PARAM_SAML);
String decodedMessage = new String(Base64.decodeBase64(encodedMessage.getBytes()));
DefaultBootstrap.bootstrap();
BasicParserPool ppMgr = new BasicParserPool();
ppMgr.setNamespaceAware(true);
Document responseRoot = ppMgr.parse(new StringReader(decodedMessage));
UnmarshallerFactory unmarshallFactory = Configuration.getUnmarshallerFactory();
Unmarshaller unmarshaller = unmarshallFactory.getUnmarshaller(responseRoot.getDocumentElement());
XMLObject obj = unmarshaller.unmarshall(responseRoot.getDocumentElement());

Using ComponentSpace SAML to sign and post request

I am using component space libraries to create SAML request and sign it then post it to URL, However request is not posting successfully because i need to use RSA algorithm key but so far i found that it is not available in SamlKeyAlgorithm also i need to change the Key size to 2048 below are my method that i used to send the request.
private void SendTawtheeqRequest()
{
string ConsumerServiceUrl = "https://tawtheeq.sa:8443/identity-gateway-test/ReceiveSAMLRequest";
// Create a SAML response object.
Response samlResponse = new Response();
// Assign the consumer service url.
samlResponse.Destination = ConsumerServiceUrl;
Issuer issuer = new Issuer(GetAbsoluteUrl("~/"));
samlResponse.Issuer = issuer;
samlResponse.Status = new Status(SamlPrimaryStatusCode.Success, null);
Assertion samlAssertion = new Assertion();
samlAssertion.Issuer = issuer;
// Use the local user's local identity.
Subject subject = new Subject(new NameId(User.Identity.Name));
SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
subjectConfirmationData.Recipient = ConsumerServiceUrl;
subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
subject.SubjectConfirmations.Add(subjectConfirmation);
samlAssertion.Subject = subject;
// Create a new authentication statement.
AuthnStatement authnStatement = new AuthnStatement();
authnStatement.AuthnContext = new AuthnContext();
authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticationContext.Password);
samlAssertion.Statements.Add(authnStatement);
X509Certificate2 encryptingCert = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "my-bank1-public.cer"));
EncryptedAssertion encryptedSamlAssertion = new EncryptedAssertion(samlAssertion, encryptingCert, new EncryptionMethod(SamlKeyAlgorithm.TripleDesCbc));
samlResponse.Assertions.Add(encryptedSamlAssertion);
samlResponse.Assertions.Add(samlAssertion);
samlResponse.SendHttpPost(Response.OutputStream, ConsumerServiceUrl, "10");
}

Spring ldap unlocking an account

I am trying to unlock user account using spring ldap and getting the error message
""Malformed 'LockoutTime' attribute value" exception.
My code looks like below
public boolean unlockAccount(Name dn) {
ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("lockoutTime", 0));
ldapTemplate.modifyAttributes(dn, new ModificationItem[] {item});
return true;
}
I am using Windows server 2016 and Spring ldap 2.3.2.
Is 'lockoutTime' the correct attribute to unlock an account ?
Is there anything else I am missing ?
In LDAP if you type the wrong password for more than 5 times, the account gets locked. If you want to unlock the user you have to delete an operational attribute name as pwdAccountLockedTime.
public String unlockUser(Users pvo) {
System.out.println("this is pvo" + pvo);
Name dn = buildDn(pvo);
DirContextOperations context = ldapTemplate.lookupContext(dn);
ModificationItem[] modificationItems;
modificationItems = new ModificationItem[1];
modificationItems[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
new BasicAttribute("pwdAccountLockedTime"));
ldapTemplate.modifyAttributes(dn, modificationItems);
return "Account Unlocked";
}
build Dn for your LDAP and use the above code then the user gets unlocked.
String[] attrIDs = new String[] { "lockoutTime", "sAMAccountName",
"distinguishedName","pwdLastSet", "accountExpires", "userAccountControl",
"IsAccountLocked" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(2);
String filter = "(&(objectClass=user)(objectCategory=Person)(sAMAccountName=" +
samaccountname+ "))";
NamingEnumeration<SearchResult> answer = ctx.search(adManagedOU, filter,ctls);
while (answer.hasMore()) {
SearchResult rs = answer.next();
Attributes attrs = rs.getAttributes();
distinguishedName = rs.getNameInNamespace();
String[] lockouttime = null;
String lockOutValue=attrs.get("lockoutTime");
if (lockOutValue != null)
{
lockouttime = attrs.get("lockoutTime").toString().split(":");
if (Long.valueOf(lockouttime[1].trim()) > 0) {
ModificationItem[] mods1 = new ModificationItem[] {
new ModificationItem(2, new BasicAttribute("lockoutTime", "0") )
};
((DirContext) ctls).modifyAttributes(distinguishedName, mods1);
}
else
{
LOGGER.info(username + " Account Not Locked");
}
The only values that may be set on lockouttime is to set the value to "0" which will effectively un-lock the account.
To learn more on Microsoft Active Directory Lockouts.
Setting the value to a String instead of an int makes this work, at least with AWS Simple AD.
ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("lockoutTime", "0"));
ldapTemplate.modifyAttributes(dn, new ModificationItem[] {item});

SQLite Database is not working after standalone build in Unity3D

I am trying to make a Standalone Application using SQLite in Unity3D,
I am getting a strange problem.
I created a database using sqliteadmin, and created a Table named Admin, having field: id, email, password.
I am able to Login using email and password but in Unity Edit Mode.
Its working fine but when i build it and then run it, its not working, I have no idea why?
Reference
Here is my code:
using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.Data;
using System;
using UnityEngine.UI;
public class DatabaseConnection : MonoBehaviour {
public Text em;
public Text pas;
public static int id;
public static string email ="";
public static string password="";
public static string wrong="Wrong Email/Password !!!";
public Text Wrong;
public GameObject loading;
private ButtonsController bc;
public GameObject loginPanel;
void Start () {
string conn = "URI=file:" + Application.dataPath + "/Database/TMDB.s3db";
IDbConnection dbconn;
dbconn = (IDbConnection)new SqliteConnection (conn);
dbconn.Open ();
IDbCommand dbcmd = dbconn.CreateCommand ();
string sqlQuery = "SELECT id, email, password " + "FROM Admin";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader ();
while (reader.Read()) {
id = reader.GetInt32 (0);
email = reader.GetString(1);
password = reader.GetString(2);
}
reader.Close ();
reader = null;
dbcmd.Dispose ();
dbcmd = null;
dbconn.Close ();
dbconn = null;
loading.SetActive (false);
}
public void login()
{
if ((em.text == email) && (pas.text == password)) {
Debug.Log ("Success");
loading.SetActive (true);
loginPanel.SetActive(false);
Application.LoadLevel(1);
} else {
Debug.Log ("Error");
Wrong.text = wrong.ToString ();
}
}
}
Application.datapath is readonly.
What you need is Application.persistentDataPath
Checkout this link
http://answers.unity3d.com/questions/209108/when-to-use-persistentdatapath-versus-datapath.html
Create StreamingAssets folder into your Assets, and use this connection string:
string conn = "URI=file:" +
System.IO.Path.Combine(Application.streamingAssetsPath, "Database/TMDB.s3db");
Using streaming asset is necessary, it places files into the normal filesystem on the target machine to make them accessible via a pathname.
More info:
https://docs.unity3d.com/Manual/StreamingAssets.html
dude ,,, just check the files bro,,, after building the database is empty so go and replace the database file with the one u been working on with the same database name .

Resources