Configure shiro.ini for JDBC connection - apache

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

Related

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.

Implementing Poor Man's SSO in Apache Shiro

Good day. I have a scenario where we have multiple web applications running on the same server and we would like one login to serve all applications. Currently, if you switch applications, you need to be re-authenticated. Try as I may, I can not get this resolved.
I went through the session management page to try and implement what they call Poor Man's SSO (https://shiro.apache.org/session-management.html)
Here is my shiro.ini:
[main]
contextFactory = org.apache.shiro.realm.ldap.JndiLdapContextFactory
contextFactory.url = ldap://1.2.3.4:389
contextFactory.systemUsername = me#testdomain.local
contextFactory.systemPassword = Password
realm = com.me.shared.security.shiro.meADRealm
realm.ldapContextFactory = $contextFactory
realm.searchBase = OU=ME,DC=testdomain,DC=local
securityManager.realms = $realm
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionIdCookie=org.apache.shiro.web.servlet.SimpleCookie
sessionIdCookie.name=sid
sessionIdCookie.maxAge=1800
sessionIdCookie.httpOnly=true
sessionManager.sessionIdCookie=$sessionIdCookie
sessionManager.sessionIdCookieEnabled=true
securityManager.sessionManager = $sessionManager
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
securityManager.sessionManager.sessionDAO = $sessionDAO
sessionValidationScheduler = org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler
sessionValidationScheduler.interval = 3600000
securityManager.sessionManager.sessionValidationScheduler = $sessionValidationScheduler
cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
securityManager.cacheManager = $cacheManager
URL mapping is done in a custom java IniWebEnvironment and looks like this
/faces/common/Login.xhtml = authc
/faces/common/unauthorized.xhtml = anon
/faces/secured/** = authc
/faces/myAdmin/** = roles[administrator]
/faces/myManagement/** = roles[administrator]
/faces/people/** = roles[administrator]
I have a custom JSF bean where I perform login like this:
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(getUserName(), getPassword());
subject.login(token);
I am open to doing SSO in a different fashion, but this is an internal application and doesn't need much. Any ideas?

Access Control In Airpal : shiro_static_users.ini

I am not able to access airpal through username and password that i provides in shiro_static_users.ini file , After the changes done i had compile the code and start the airpal server :
Without giving any username and password i am able to access the airpal server.
I have pm as a database in hive and want to give permission to raj user.
My ini file:
authc = org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter
shiro.loginUrl = /login
authc.successUrl = /app
allGroup = com.airbnb.shiro.UserGroup
allGroup.groups = all
allGroup.permissions = access, read:*:*, write:*:*
allGroup.defaultConnector = hive
allGroup.defaultSchema = default
allGroup.timeout = 40m
allGroup.accessLevel = User
allGroup1 = com.airbnb.shiro.UserGroup
allGroup1.groups = pm
allGroup1.permissions = access, read:*:*, write:*:*
allGroup1.defaultConnector = hive
allGroup1.defaultSchema = pm
allGroup1.timeout = 40m
allGroup1.accessLevel = User
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionListener = com.airbnb.shiro.SessionListenerLogger
allowAllFilter = com.airbnb.shiro.filter.AllowAllFilter
allowAllFilter.groups = $allGroup ,$allGroup1
allowAllFilter.loginUrl = /login
securityManager.sessionManager = $sessionManager
[users]
test = test, all
raj = raj, pm
[roles]
all = *
pm = *
[urls]
/login = authc
/logout = logout
/app = authc, perms["access"]
/api/** = authc, perms["access"]

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

Apache Shiro, isPermitted() isnĀ“t working

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