0

我试图从 StackOverflow(使用 Spring Security 和 JPA)中关注这篇文章但没有成功。

我实现了一个 UserDetailsS​​ervice:

import javax.inject.Inject;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.boss.mrfoods.dao.UserDao;
import com.boss.mrfoods.entity.User;

@Service
public class LoginController implements UserDetailsService {

    @Inject
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        User user = userDao.getForUsername(username);

        System.out.println("USERNAME: " + username);
        System.out.println("USER: " + user);
        System.out.println("ROLES:" + user.getRoles());

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getRoles());
    }

}

并在 Spring XML 配置文件之一中引用它,如下所示:

<debug />

<global-method-security pre-post-annotations="enabled" />

<http pattern="/resources/**" security="none" />
<http pattern="/pages/loggedout.xhtml" security="none" />
<http pattern="/pages/timeout.xhtml" security="none" />

<http use-expressions="true">
    <intercept-url pattern="/pages/admin/**" access="hasRole('supervisor')" />
    <intercept-url pattern="/pages/user/**" access="isAuthenticated()" />
    <intercept-url pattern="/**" access="permitAll" />
    <form-login />
    <logout logout-success-url="/pages/loggedout.xhtml" delete-cookies="JSESSIONID" />
    <remember-me />
</http>

<beans:bean id="customUserDetailsService" class="com.boss.mrfoods.controller.LoginController" />

<authentication-manager>
    <authentication-provider user-service-ref="customUserDetailsService">
        <password-encoder hash="plaintext" />
    </authentication-provider>
</authentication-manager>

什么都没发生。没有例外,我的 UserDetailsS​​ervice 实现永远不会被调用。

我想要归档的是 Spring Security 使用我的 JPA 连接/事务来查找用户/角色。我缺少配置吗?如果我什至没有得到异常,我从哪里开始寻找问题。

到目前为止我发现的是:我的 userDao 是空的。对象注入不起作用。Inject 无法构建对象。为什么?

感谢您阅读本文。

4

1 回答 1

0

您能否详细说明您是如何登录到该应用程序的。您是否直接访问用户页面并期待登录页面?

您是否尝试过像这样设置登录页面,

 <form-login
        login-page="/login.html"
        login-processing-url="/j_spring_security_check.action"
        authentication-failure-url="/login_error.html"
        default-target-url="/home.html"
        always-use-default-target="true"/>
于 2013-02-27T20:46:50.873 回答