Apache Shiro, isPermitted() isn´t working - permissions

I'm making some testing with Apache Shiro just for learn, and i have a problem with permissions. The method isPermitted() just not work I mean, it's always return false.
shiro.ini
[main]
sha256Matcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
sha256Matcher.hashAlgorithmName=SHA-256
authc.loginUrl = /faces/views/login.xhtml
authc.successUrl = /faces/views/index.xhtml
builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $builtInCacheManager
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = select senha from VUsuarioPerfil where usuario = ?
jdbcRealm.userRolesQuery = select perfil from VUsuarioPerfil where usuario = ?
jdbcRealm.permissionsQuery = select permissoes from VUsuarioPerfil where usuario = ?
jdbcRealm.credentialsMatcher = $sha256Matcher
ds = com.microsoft.sqlserver.jdbc.SQLServerConnectionPoolDataSource
ds.serverName = 192.168.50.254
ds.user = xx
ds.password = xxx
ds.databaseName = shiro
jdbcRealm.dataSource = $ds
Each user should have his own permission, so on the view(VUsuarioPerfil) there is a column called permissoes where I placed a string, like "clientes:visualizar".
And on code I test this way
public void test() {
System.out.println(SecurityUtils.getSubject().hasRole("usuario"));
System.out.println(SecurityUtils.getSubject().isPermitted("clientes:visualizar"));
}
Result is output:
true
false
I don't now why just the permission isn't caught on database.

In the JDBC realm, the permissions query is not expected to map users->roles, it is expected to map roles->permissions.
So essentially, the query that is getting called is:
select permissoes from VUsuarioPerfil where usuario = usuario
And, as you would expect, it returns nothing. Therefore the role has no permissions, and the user has no permissions.
Perhaps considering the default permissions query would help you think about how to map a query to your data structure?
select permission from roles_permissions where role_name = ?

Check out your property:
select permissoes from VUsuarioPerfil
You need to correct permissions

Related

Login failed for user token-identified principal when connecting via sql_driver_manager.getConnection

I am trying to connect to Azure SQL using Service Principle to create views, but it says
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ClientConnectionId: XXXXX-XXXX-XXXX
However, with the same SPN I was able to connect and create tables, read tables.
import adal
resource_app_id_url = "https://database.windows.net/"
service_principal_id = dbutils.secrets.get(scope = "XX", key = "XXX")
service_principal_secret = dbutils.secrets.get(scope = "XX", key = "spn-XXXX")
tenant_id = dbutils.secrets.get(scope = "XX", key = "xxId")
authority = "https://login.windows.net/" + tenant_id
azure_sql_url = "jdbc:sqlserver://xxxxxxx.windows.net"
database_name = "testDatabase"
encrypt = "true"
host_name_in_certificate = "*.database.windows.net"
context = adal.AuthenticationContext(authority)
token = context.acquire_token_with_client_credentials(resource_app_id_url, service_principal_id, service_principal_secret)
access_token = token["accessToken"]
using above code I am able to create and read tables. There is a requirement to create views so I am using sql_driver_manager to connect to Azure SQL
properties = spark._sc._gateway.jvm.java.util.Properties()
properties.setProperty("accessToken", access_token)
sql_driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
sql_con = sql_driver_manager.getConnection(azure_sql_url, properties)
query = """
create or alter view test_view as select * from dbo.test_table
"""
stmt = sql_con.createStatement()
stmt.executeUpdate(query)
stmt.close()
this is resulting in an error:
Py4JJavaError: An error occurred while calling
z:java.sql.DriverManager.getConnection. :
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user token-identified principal. ClientConnectionId:
If I try the same with username and password instead of token, it works but I just need to use spn token for authenticating.
Working code:
sql_driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
sql_con = sql_driver_manager.getConnection(azure_sql_url, username, password)
query = """
create or alter view test_view as select * from dbo.test_table
"""
stmt = sql_con.createStatement()
stmt.executeUpdate(query)
stmt.close()
What is that I am missing, can someone help me understand the issue. Thanks.
You can not use that method since it was built to execute an update statement and return indexes.
See documentation. Use the prepare() and execute() methods.
https://learn.microsoft.com/mt-mt/sql/connect/jdbc/reference/executeupdate-method-java-lang-string?view=azuresqldb-current
#
# 5 - Upsert from stage to active table.
# Grab driver manager conn, exec sp
#
driver_manager = spark._sc._gateway.jvm.java.sql.DriverManager
connection = driver_manager.getConnection(url, user_name, password)
connection.prepareCall("exec [stage].[UpsertFactInternetSales]").execute()
connection.close()
This is sample code from an article I wrote. It calls a stored procedure to execute an UPSERT. However, any DML or DDL will work as long as it does not return a result set.

Gerrit LDAP mandatoryGroup

How do config mandatoryGroup in Gerrit's LDAP? My gerrit.conf is currently like this... I'm not sure if the mandatoryGroup value should be LDAP syntax or plan text. I can not figure this out based on documentation.
https://gerrit-review.googlesource.com/Documentation/config-gerrit.html#ldap
ldap.mandatoryGroup
All users must be a member of this group to allow account creation or authentication.
Setting mandatoryGroup implies enabling of ldap.fetchMemberOfEagerly
By default, unset.
gerrit.config
[ldap]
server = ldaps://company.com
sslVerify = false
username = ldapUsername
password = ldapPassword
accountBase = DC=COMPANY_DOMAIN,DC=LOCAL
groupBase = DC=COMPANY_DOMAIN,DC=LOCAL
referral = follow
accountPattern = (sAMAccountName=${username})
groupPattern = (cn=${groupname})
accountFullName = displayName
accountMemberField = memberOf
accountEmailAddress = mail
mandatoryGroup = grp_IT_SourceCode
mandatoryGroup = ldap/"AD_Group_Name" worked for me... I'm not sure why but the "ldap/" was required before the AD group and all is good now.

Configure a DataSource in TomEE in system.properties instead of tomee.conf

I'm able to configure a DataSource Resource in TomEE by modifying the "conf/tomee.xml" file. However, it's sort of awkward to automate this modification, as I have to insert the DataSource definition before the "" line. I heard from a comment in a related SO posting from me that it's easier to append to the "system.properties" file.
So, I tried translating this:
<Resource id="sus2" type="DataSource">
JdbcDriver = oracle.jdbc.driver.OracleDriver
MaxActive = 10
MinIdle = 2
MaxIdle = 2
MaxWait = 10000
JdbcUrl = jdbc:oracle:thin:#${DB_HOST}:${DB_PORT}:${DB_SID}
UserName = ${DB_USER}
Password = ${DB_PASSWORD}
</Resource>
Which works, to the following:
db = new://Resource?type=DataSource
db.id = Resource/sus2
db.JdbcDriver = oracle.jdbc.driver.OracleDriver
db.MaxActive = 10
db.MinIdle = 2
db.MaxIdle = 2
db.MaxWait = 10000
db.JdbcUrl = jdbc:oracle:thin:#${DB_HOST}:${DB_PORT}:${DB_SID}
db.UserName = ${DB_USER}
db.Password = ${DB_PASSWORD}
which does not work. It fails, saying it couldn't find the "Resource/sus2" resource.
The configuration reference can be found at http://tomee.apache.org/ng/admin/configuration/resources.html
You have to understand that XML attributes becomes URI query parameters then I think it will work.
In other words:
db = new://Resource?type=DataSource
becomes
sus2 = new://Resource?type=DataSource
and your db.id doesn't do anything - I think it is logged.
In short: replace all your "db" by "sus2" and it will work

Configure shiro.ini for JDBC connection

As part of my new years learning new technologies initiative I have started messing around with the Apache Shiro Security Framework.
I managed to get the basic example working which stores usernames, passwords and roles in the shiro.ini file, but when I modified my shiro.ini file to use JDBC it just stopped working. I now keep getting prompted for my username and password when trying to access my application. I've kept it as simple as possible (the passwords aren't even hashed).
Below is my shiro.ini file, does anyone have any idea what I'm doing wrong?
[main]
authc.usernameParam = j_username
authc.passwordParam = j_password
authc.failureKeyAttribute = shiroLoginFailure
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = "SELECT password FROM user WHERE username = ?"
jdbcRealm.userRolesQuery = "SELECT role FROM user WHERE username = ?"
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.serverName = localhost
ds.user = root
ds.password = password
ds.databaseName = database
jdbcRealm.dataSource = $ds
# Use Built-in Chache Manager
builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $builtInCacheManager
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
/* = authcBasic
If you are not giving permission query then better disable permission lookup. Also if you want to use basic Authentication why use authc attributes.
Try Following
[main]
#authc.usernameParam = j_username
#authc.passwordParam = j_password
#authc.failureKeyAttribute = shiroLoginFailure
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = false
jdbcRealm.authenticationQuery = SELECT password FROM user WHERE username = ?
jdbcRealm.userRolesQuery = SELECT role FROM user WHERE username = ?
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.serverName = localhost
ds.user = root
ds.password = password
ds.databaseName = database
jdbcRealm.dataSource = $ds
# Use Built-in Chache Manager
builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $builtInCacheManager
securityManager.realms = $jdbcRealm
[users]
[roles]
[urls]
/* = authcBasic

Apache Shiro login failed using JDBC Realm

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