自动装配在Apache Shiro自定义Realm类中不起作用

时间:2017-10-23 04:59:24

标签: java spring-boot spring-security annotations shiro

目前我在Spring启动项目中使用apache shiro身份验证。我为Cassandra DB写了Custom Realm。在提交登录详细信息时,在realm对象内自动装配类会返回null。我的应用程序配置(使用@component注释):

@Bean(name = "realm")
@DependsOn("lifecycleBeanPostProcessor")
public ApplicationRealm realm() {
    ApplicationRealm realm = new ApplicationRealm();
    realm.init();
    return realm;
}

@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
    return new LifecycleBeanPostProcessor();
}

我的应用领域类:

 @Configuration
 @ComponentScan("com.scm.auth")
public class ApplicationRealm extends AuthorizingRealm {

@Autowired
IAuthRepository authRepo;

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    Set<String> roles = new HashSet<String>();
    try {
        roles.add("admin");
    } catch (Exception rEx) {
        throw new AuthorizationException(rEx);
    }
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
    info.setRoles(roles);

    return info;
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    SimpleAuthenticationInfo info = null;
    UsernamePasswordToken upToken = (UsernamePasswordToken) token;

    User user = authRepo.findByUserName(upToken.getUsername(), true); // my model class

        try {
            if (user.getCurrentPwd().equals(upToken.getPassword())) {
                info = new SimpleAuthenticationInfo(user, user.getCurrentPwd(), getName());
            } else {
                throw new AuthenticationException("Login name [" + upToken.getUsername() + "] not found!");
            }
        } catch (Exception idEx) {
            throw new AuthenticationException(idEx);
        }
        return info;


}

是否遗漏了任何注释?

1 个答案:

答案 0 :(得分:1)

好像你配置了不匹配的注释。您的ApplicationRealm.java应该没有@Configuration注释。 @Component对于这个Custome领域来说足够了。

 /*@Configuration*/
 @ComponentScan("com.scm.auth")
 public class ApplicationRealm extends AuthorizingRealm{
 /**/
 }