首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用服务的Spring安全不会自动编写依赖项,并会给出空指针异常

使用服务的Spring安全不会自动编写依赖项,并会给出空指针异常
EN

Stack Overflow用户
提问于 2018-03-02 20:24:04
回答 2查看 127关注 0票数 0

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

代码语言:javascript
复制
@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文件:

代码语言:javascript
复制
<?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>
EN

回答 2

Stack Overflow用户

发布于 2018-03-02 21:21:45

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

你应该对你的Dao使用@Autowired

代码语言:javascript
复制
@Autowired
private KnowledgeBaseDao knowledgeBaseDao;

别忘了扫描dao包

票数 1
EN

Stack Overflow用户

发布于 2018-03-02 21:46:44

因此,我通过在sequrity中显式定义所需的bean并从userservice类中删除任何自动连接的注释来解决这个问题:

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49069108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档