1

我正在尝试为我的 Web 应用程序使用 Spring 安全性。我即将制作登录功能,以便用户可以登录到我网站中的安全页面。到目前为止,我一直在使用 Spring security's own ,在那里我使用了内存数据存储进行身份验证(主要是为了测试它是否有效,因为我还在学习。)

当我尝试使用存储了不同用户的数据库时,就会出现我的问题。当我尝试登录时,spring security 会将我重定向到我的“authentication-failure-url”,而不是让我登录。

我创建了一个自定义 UserDetails 类

package dk.chakula.web.security;

import dk.chakula.web.domain.User;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
 *
 * @author Martin Rohwedder
 * @since 20-02-2013
 * @version 1.0
 */
public class ChakulaUserDetails implements UserDetails {

    private User user;
    private List<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    public ChakulaUserDetails(User user, List<? extends GrantedAuthority> authorities)         {
        this.user = user;
        this.authorities = authorities;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.user.getPassword();
    }

    @Override
    public String getUsername() {
        return this.user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}

我还创建了一个自定义 UserDetailsS​​ervice,我的“身份验证提供者”正在引用它。那堂课看起来像这样。

package dk.chakula.web.security;

import dk.chakula.web.domain.User;
import dk.chakula.web.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.Component;
/**
 *
 * @author Martin Rohwedder
 * @since 20-02-2013
 * @version 1.0
 */
@Component("chakulaUserDetailsService")
public class ChakulaUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("Username was empty");
        }

        User user = userService.getUserByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("User with username '" + username + "' was not found");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        grantedAuthorities.add(new SimpleGrantedAuthority(user.getUserRole()));

        return new ChakulaUserDetails(user, grantedAuthorities);
    }

}

我的完整春季安全上下文如下所示

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

    <security:http use-expressions="true">

        <!-- Form Login Filter -->
        <security:form-login login-page="/login" default-target-url="/app/start" authentication-failure-url="/login?authenticationNok=1" username-parameter="username" password-parameter="password" always-use-default-target="true" />

        <!-- Logout Filter -->
        <security:logout logout-success-url="/home?logoutOk=1" logout-url="/logout" invalidate-session="true" />

        <!-- Intercept Url filters -->
        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/home" access="permitAll" />
        <security:intercept-url pattern="/about" access="permitAll" />
        <security:intercept-url pattern="/login" access="permitAll" />
        <security:intercept-url pattern="/resources/**" access="permitAll" />

        <security:intercept-url pattern="/app/**" access="fullyAuthenticated" />

    </security:http>

    <bean id="chakulaUserDetailsService" class="dk.chakula.web.security.ChakulaUserDetailsService" />

    <security:authentication-manager>
        <security:authentication-provider user-service-ref="chakulaUserDetailsService">
            <security:password-encoder hash="sha-256">
                <security:salt-source user-property="username" />
            </security:password-encoder>
            <!--
            <security:user-service>
                <security:user name="test" password="e9233bd61e14137a7e28f92c50ce279215e774a1772d1e9dad5f275b9cc8177c" authorities="ROLE_CUSTOMER" />
            </security:user-service>
            -->
        </security:authentication-provider>
    </security:authentication-manager>

</beans>

您可以查看我在 GITHUB 上的 Chakula 项目中的所有源代码,如果您需要它来帮助我 - https://github.com/martin-rohwedder/chakula

4

1 回答 1

0

这似乎是我的 Dao 实现类的失败,因为当我显示 AuthenticationException 的消息时,它告诉我以下内容 - 无法解析属性: USERNAME of: dk.chakula.web.domain.User [来自 dk.chakula .web.domain.User u 其中 u.USERNAME = :USERNAME]

我所要做的就是用非大写字母写 u.USERNAME。

我用以下值改写了我的安全上下文 xml 文件 form-login tags authentication-failure-url 属性。

 <security:form-login login-page="/login" default-target-url="/app/start" authentication-failure-url="/login/failure" username-parameter="username" password-parameter="password" always-use-default-target="true" />

此后,我在 AuthenticationController 中创建了一个新方法来呈现失败视图,并将 AuthenticationException 消息作为模型添加到视图中

@RequestMapping(value = {"/login/failure"}, method = RequestMethod.GET)
public ModelAndView renderLoginFailureView(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView("login");
    AuthenticationException authEx = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

    mav.addObject("authEx", authEx.getMessage());
    return mav;
}

下次我知道在冲入 stackoverflow 之前显示所有异常消息。尽管现在其他人将来可能会从我的回答中受益。

感谢 Arun P Johny 在这里帮助我。

于 2013-02-21T12:16:44.057 回答