我试图将我的UserDAO注入到Apache Shiro正在使用的自定义AuthorizingRealm中,但是...我得到空值。无法在自定义Apache Shiro中注入我的DAO AuthorizingRealm
我在做什么错?
shiro.ini
[main]
user = demo.shiro.security.FacesAjaxAwareUserFilter
realmA = demo.shiro.security.JpaRealm
credentialsMatcher = org.apache.shiro.authc.credential.SimpleCredentialsMatcher
realmA.credentialsMatcher = $credentialsMatcher
securityManager.realms = $realmA
user.loginUrl = /pages/public/login.xhtml
[users]
admin = admin
user = user
[urls]
# public files and folders
/index.html = anon
/resources/** = anon
/pages/public/** = anon
# restricted files and folders
/pages/admin/** = user
/pages/user/** = user
JpaRealm.java
public class JpaRealm extends AuthorizingRealm {
@Inject
private UserDao userDao;
public JpaRealm() {
setCredentialsMatcher(new Sha256CredentialsMatcher());
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authToken;
User user = userDao.getForUsername(token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
} else {
return null;
}
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Long userId = (Long) principals.fromRealm(getName()).iterator().next();
User user = userDao.findByKey(userId);
if (user != null) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Role role : user.getRoles()) {
info.addRole(role.getDescription());
for (Permition permition : role.getPermitions()) {
info.addStringPermission(permition.getDescription());
}
}
return info;
} else {
return null;
}
}
}
我必须做的,让CDI要意识到@Inject我的自定义领域内,妥善注入我的UserDAO?
出色答卷!但我有一个问题:是什么让这个自定义EnvironmentLoaderListener“CDI意识到”?注入注释?这个监听器实现是否使shiro.ini conf过时了?因为我们正在设定一个固定的领域: rsm。setRealm(jpaRealm); – salihcenap 2013-07-23 10:57:22
我包含了更多的代码来回答“CDI意识”部分(请参阅JpaRealm.java)。不知怎的,shiro.ini并没有被废弃......你需要它来定义一些配置......删除它会导致很多问题。如果你打算建立一个shiro.ini免费安全,我认为这将是非常好的。 – MBarni 2013-08-01 12:33:01
Juste一个问题,你为什么从你的shiro.ini中删除realmA? (或只是为了简洁?)。 tnx – mboullouz 2015-04-11 21:23:47