使用服务的Spring安全性不会自动赋予依赖关系并给出空指针异常

时间:2018-03-02 12:24:04

标签: spring spring-security

我的UserService出现问题。它无法识别其中定义的自动连接依赖项。我尝试直接在变量和构造函数上使用Autowired注释。 knowledgbaseDao中的loadUserByUsername为空。在启动时,此类的构造函数被调用3次。每个创建不同的对象。第一个是使用默认的空构造函数创建的。其他两个是使用自动装配的构造函数创建的,并为knowledgebaseDao指定正确的类。当从登录页面调用userservice时,它使用第一个UserService类并抛出空指针异常。这是我的代码:

@Component("userService")
public class UserService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private KnowledgeBaseDao knowledgeBaseDao;

    public UserService(){
        System.out.println();
    }

    @Autowired
    public UserService(KnowledgeBaseDao knowledgeBaseDao) {
        this.knowledgeBaseDao = knowledgeBaseDao;
        }

    public UserDetails loadUserByUsername(String login) throws AuthenticationException {
        logger.info("UserDetails Database Service : " + login);

        // check user exists in database
        User user = knowledgeBaseDao.findUserByEmail(login);
        if (user == null) {
            logger.warn("User({}) does not exist in system", login);
            throw new UsernameNotFoundException("There is no user with this username.");
        }

        boolean containsLoginRole = checkLoginRole(user);

        if (!containsLoginRole) {
            throw new UsernameNotFoundException("Access denied.");
        }

        if ((user.getStatus() == null || user.getStatus() == 0)) {
            throw new UsernameNotFoundException("User is not confirmed");
        }

        //boolean enabled = user.getStatus() == AccountStatus.ACTIVE;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        if (user.getLoginTryCount() != null && user.getLoginTryCount() >= 3) {
            accountNonLocked = false;
        }

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), true, accountNonExpired,
                credentialsNonExpired, accountNonLocked, this.getAuthorities(user.getRoleId()));
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roleList) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Long roleId) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        authorities.add(new SimpleGrantedAuthority(Constants.ROLE_NAME(roleId.intValue())));

        return authorities;
    }

    private boolean checkLoginRole(User user) {
        if (user.getRoleId() == 0) {
            return false;
        }

        if (user.getRoleId() == Constants.ROLE_ADMIN
                || user.getRoleId() == Constants.ROLE_MODERATOR
                || user.getRoleId() == Constants.ROLE_USER) {
            return true;
        } else {
            return false;
        }
    }
}

更新:

这是security.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Disabled Security for Static Resources -->
    <global-method-security pre-post-annotations="enabled" secured-annotations="enabled"/>
    <http pattern="/static/**" security="none"/>

    <beans:bean id="shaPasswordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
        <beans:constructor-arg value="256"/>
    </beans:bean>

    <beans:bean id="userService" class="com.gsu.knowledgebase.service.UserService"/>

    <!-- Ajax Aware Handler -->
    <beans:bean id="authEntryPoint"
                class="com.gsu.knowledgebase.spring.AjaxAwareLoginUrlAuthenticationEntryPoint"
                scope="singleton">
        <beans:constructor-arg name="loginFormUrl" value="/knowledge-base"/>
    </beans:bean>

    <http authentication-manager-ref="authenticationManager" entry-point-ref="authEntryPoint"
          pattern="/knowledge-base/**"
          use-expressions="true" disable-url-rewriting="true">

        <custom-filter position="BASIC_AUTH_FILTER" ref="loginFilter"/>
        <logout logout-success-url="/knowledge-base" invalidate-session="true" delete-cookies="JSESSIONID"
                logout-url="/knowledgeBase/j_spring_security_logout"/>

        <intercept-url pattern="/knowledge-base/" access="permitAll"/>
        <intercept-url pattern="/knowledge-base/memory"
                       access="hasRole('ADMIN') || hasRole('MODERATOR') || hasRole('USER')"/>

        <access-denied-handler error-page="/knowledge-base/error/403"/>
        <session-management session-authentication-error-url="/knowledge-base/error/sessionExpired"/>
    </http>

    <!-- ************************** -->

    <authentication-manager id="authenticationManager">
        <authentication-provider user-service-ref="userService">
            <password-encoder ref="shaPasswordEncoder"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginFilter"
                class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <beans:property name="authenticationManager" ref="authenticationManager"/>
        <beans:property name="filterProcessesUrl" value="/knowledgeBase/j_spring_security_check"/>
        <beans:property name="authenticationSuccessHandler">
            <beans:bean class="com.gsu.knowledgebase.spring.AuthenticationSuccessHandler"/>
        </beans:property>
        <beans:property name="authenticationFailureHandler">
            <beans:bean class="com.gsu.knowledgebase.spring.AuthenticationFailureHandler"/>
        </beans:property>
    </beans:bean>

    <!-- ************************** -->


</beans:beans>

2 个答案:

答案 0 :(得分:1)

我在gitHub中有一个这样的项目:link

你应该在你的Dao中使用@Autowired

@Autowired
private KnowledgeBaseDao knowledgeBaseDao;

别忘了扫描dao包

答案 1 :(得分:0)

所以我通过在sequrity xml中显式定义所需的bean并从userservice类中删除任何自动连接的注释来解决它:

<beans:bean id="maxIdCalculator" class="com.gsu.common.util.MaxIdCalculator">
</beans:bean>

<beans:bean id="knowledgeBaseDao" class="com.gsu.knowledgebase.repository.KnowledgeBaseDao">
    <beans:constructor-arg ref="kbDataSource"/>
    <beans:constructor-arg ref="maxIdCalculator"/>
</beans:bean>

<beans:bean id="userService" class="com.gsu.knowledgebase.service.UserService">
    <beans:constructor-arg ref="knowledgeBaseDao"/>
</beans:bean>