Apache Shiro login failed using JDBC Realm - apache

I am trying to connect to oracle DB .
I want to retrieve list of passwords from data base using the authentication query. Here is my sample shiro.ini file:
# password matcher
passwordMatcher = org.apache.shiro.authc.credential.PasswordMatcher
passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
passwordMatcher.passwordService = $passwordService
# datasource
ds = oracle.jdbc.pool.OracleDataSource
ds.URL = jdbc:oracle:thin:#matrix-oracle11g:1521:dev11g
ds.user = cit1am
ds.password = cit1
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR
jdbcRealm.credentialsMatcher = $passwordMatcher
jdbcRealm.dataSource = $ds
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
Sample code snippet of login:
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
try{
// let's login the current user so we can check against roles and permissions:
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("cit1am", "cit1") ;
token.setRememberMe(true);
try {
currentUser.login(token); //problem occurs here
log.info("inside try block ==========>>" );
}
catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
}
I am getting following error:
[main] ERROR org.apache.shiro.realm.jdbc.JdbcRealm - There was a SQL error while authenticating user [cit1am]
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
Please suggest what i am doing wrong?

After debugging more i found issue with my code and sql query in .ini file.
I changed following in .INI file
jdbcRealm.authenticationQuery = SELECT USR_PSWD FROM USR where USR_NM = ?
Also commented
#cm = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
#jdbcRealm.credentialsMatcher = $cm and removedconfiguration related to password matcher
I also removed role and permission check from java code.
As i have just started with shrio it's bit difficult to understand flow at start.
Though it can help some one in future.
Thanks

Related

Not able to establish database connection -dberror(Connection.prepareStatement): 258 - insufficient privilege: Not authorized

I am new to SAP Hana cloud environment and was trying to learn sentiment analysis using Hana cloud platform. I am using the following code in my .xsjs script :
var body = "error";
var data = {
result : 0
};
var id = Number($.request.parameters.get("id"));
var word = $.request.parameters.get("word");
if(word.length!==0) {
try {
var conn = $.db.getConnection();
var query = 'call \"com.hana.cloud.platform.TwitterSenitmentAnalysis.DatabaseStore::update\"(?,?)';
var cst = conn.prepareCall(query);
cst.setString(1, word);
cst.setInteger(2, id);
var rs = cst.execute();
conn.commit();
rs = cst.getResultSet();
while(rs.next()) {
data.result = rs.getInteger(1);
}
body = JSON.stringify(data);
rs.close();
cst.close();
conn.close();
} catch (e) {
body = e.stack + e.message;
$.response.status = $.net.http.BAD_REQUEST;
conn.close();
}
}
I am able to use another xsjs service to connect to the database and perform select however when I try to perform update it gives me the following error :
Not able to establish database connection -dberror(Connection.prepareStatement): 258 - insufficient privilege: Not authorized
The schema name I am working with is called AMRIT and the user is called AMRIT as well. While trying to give object privileges to the AMRIT schema for the update I get the following error in the hana database cockpit:
8:07:22 PM (Security Editor) Changing 'AMRIT' user failed: 404 - Granting privilege 'UPDATE' on SCHEMA 'AMRIT' failed: insufficient privilege: Not authorized
please assist on how to solve this?
Should I be giving any additional privilege to the system user?
Thanks, regards
Please give insert privilege on your schema to user _SYS_REPO.

Azure Pack REST API Authentication

After hours of search in Microsoft messed up API documentation for its products, i am still no where on how to authenticate a rest API request in windows azure pack distribution.
Primarily i want to create an API which automate the process of deploying virtual machine, but I cant find any documentation on how to acquire the authentication token to access the resources.
Some documentation states the use of ADFS, but don't provide any reference on the ADFS REST API for authentication.
And I don't want to use ADFS in the first place. I want to authenticate using AZURE tenant and admin interface.
In conclusion, if anyone can provide any help on the REST API authentication, it will make my day.
Thanks in advance.
You can use the following PowerShell to acquire an access token.
Add-Type -Path 'C:\Program Files\Microsoft Azure Active Directory Connect\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
$tenantID = "<the tenant id of you subscription>"
$authString = "https://login.windows.net/$tenantID"
# It must be an MFA-disabled admin.
$username = "<the username>"
$password = "<the password>"
# The resource can be https://graph.windows.net/ if you are using graph api.
# Or, https://management.azure.com/ if you are using ARM.
$resource = "https://management.core.windows.net/"
# This is the common client id.
$client_id = "1950a258-227b-4e31-a9cf-717495945fc2"
$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" `
-ArgumentList $username,$password
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" `
-ArgumentList $authString
$authenticationResult = $authContext.AcquireToken($resource,$client_id,$creds)
# An Authorization header can be formed like this.
$authHeader = $authenticationResult.AccessTokenType + " " + $authenticationResult.AccessToken
I am doing some similar job like you did.
static string GetAspAuthToken(string authSiteEndPoint, string userName, string password)
{
var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));
var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
identityProviderBinding.Security.Message.EstablishSecurityContext = false;
identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
{
TrustVersion = TrustVersion.WSTrust13,
};
//This line is only if we're using self-signed certs in the installation
trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
trustChannelFactory.Credentials.SupportInteractive = false;
trustChannelFactory.Credentials.UserName.UserName = userName;
trustChannelFactory.Credentials.UserName.Password = password;
var channel = trustChannelFactory.CreateChannel();
var rst = new RequestSecurityToken(RequestTypes.Issue)
{
AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
TokenType = "urn:ietf:params:oauth:token-type:jwt",
KeyType = KeyTypes.Bearer,
};
RequestSecurityTokenResponse rstr = null;
SecurityToken token = null;
token = channel.Issue(rst, out rstr);
var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
var jwtString = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));
return jwtString;
}
Parameter "authSiteEndPoint" is your Tenant Authentication site url.
default port is 30071.
You can find some resource here:
https://msdn.microsoft.com/en-us/library/dn479258.aspx
The sample program "SampleAuthApplication" can solve your question.

Rally: Get user _ref from RallyRestApi object created using ApiKey

I created a connection to rally using the ApiKey constructor.
Question is how do i find out the User "_ref" associated with this User ApiKey ?
rallyRestApi= new RallyRestApi(new URI(host), "myApiKey");
I tried following 2 test runs:
doing a blank query (i.e. without any setQueryFilter) on User object; it returns me all the users.
QueryRequest userRequest = new QueryRequest("User");
QueryResponse userQueryResponse = connection.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
Getting owner from Workspace object >> This returns me the owner of the Workspace
You may get a current user:
GetRequest getRequest = new GetRequest("/user");
GetResponse getResponse = restApi.get(getRequest);
JsonObject currentUser = getResponse.getObject();
String currentUserName = currentUser.get("_refObjectName").getAsString();
String currentUserRef = currentUser.get("_ref").getAsString();
System.out.println("current user: " + currentUserName + currentUserRef);
I tested it with latest Rally API toolkit for Java.

InsertAll using C# not working

I´d like to know why this code is not working. It runs without errors but rows are not inserted. I´m using C# client library.
Any ideas? Thanks!!
string SERVICE_ACCOUNT_EMAIL = "(myserviceaccountemail)";
string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"C:\(myprivatekeyfile)";
System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
new System.Security.Cryptography.X509Certificates.X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
Scopes = new[] { BigqueryService.Scope.BigqueryInsertdata, BigqueryService.Scope.Bigquery }
}.FromCertificate(certificate));
// Create the service.
var service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "test"
});
Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest tabreq = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest();
List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData> tabrows = new List<Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData>();
Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData rd = new Google.Apis.Bigquery.v2.Data.TableDataInsertAllRequest.RowsData();
IDictionary<string,object> r = new Dictionary<string,object>();
r.Add("campo1", "test4");
r.Add("campo2", "test5");
rd.Json = r;
tabrows.Add(rd);
tabreq.Rows = tabrows;
service.Tabledata.InsertAll(tabreq, "(myprojectid)", "spots", "spots");
I think you should add the Kind field [1]. It should be something like this:
tabreq.Kind = "bigquery#tableDataInsertAllRequest";
Also remeber that every request of the API has a response [2] with additional info to help you find the issue's root cause.
var requestResponse = service.Tabledata.InsertAll(tabreq, "(myprojectid)", "spots", "spots");
[1] https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1Data_1_1TableDataInsertAllRequest.html#aa2e9b0da5e15b158ae0d107378376b26
[2] https://cloud.google.com/bigquery/docs/reference/v2/tabledata/insertAll

Hippo cms add content to repository

This time I'm trying add a values to repository using component. I don't have problem with reading.
Currently, I'm trying add the city to the repository
My code:
Session session = this.getPersistableSession(request);
HippoBean siteBaseBean = request.getRequestContext().getSiteContentBaseBean();
HippoBean hippoFolder = siteBaseBean.getBean("city");
Node node = hippoFolder.getNode();
String path = node.getPath(); // it's working "/content/documents/myhippoproject/city"
node.addNode("4","hippo:handle");
session.save();
after this code nothing happened. I tried also:
node.addNode("4",HippoNodeType.HIPPO_NODE);
No errors and node.
ok, I found a solution.
Session session = this.getPersistableSession(request);
HippoBean siteBaseBean = request.getRequestContext().getSiteContentBaseBean();
HippoBean hippoFolder = siteBaseBean.getBean("city");
Node node = hippoFolder.getNode();
HippoRepository repository = HippoRepositoryFactory.getHippoRepository("vm://");
Session session2 = repository.login("admin", "admin".toCharArray());
HstRequestContext requestContext = request.getRequestContext();
WorkflowPersistenceManager wpm = null;
wpm = getWorkflowPersistenceManager(session2);
wpm.setWorkflowCallbackHandler(new BaseWorkflowCallbackHandler<DocumentWorkflow>() {
public void processWorkflow(DocumentWorkflow wf) throws Exception {
wf.requestPublication();
}
});
String name = "12";
wpm.createAndReturn(node.getPath(), "myhippoproject:City", name, false);
City city = (City) wpm.getObject(node.getPath() + "/" + name);
wpm.update(city);
session2.save();