1

我在实施 Spring Security 时遇到了一些问题。我正在使用自定义用户详细信息服务,当我尝试注册一个新帐户时,它似乎没有按应有的方式登录用户。这是我尝试使用 SignInUtils 类登录用户的代码

SignInUtils.java

package com.youthministry.controller;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

public class SignInUtils {
    /**
     * Programmatically signs in the user with the given the user ID.
     */
    public static void signin(String userId) {
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userId, null, null));  
    }

}

登录控制器.java

package com.youthministry.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import com.youthministry.controller.SignInUtils;
import com.youthministry.controller.SignupForm;
import com.youthministry.domain.Role;
import com.youthministry.domain.User;
import com.youthministry.domain.UserProfile;

import com.youthministry.service.UserService;

@Controller
public class LoginController {

    @Autowired
    private UserService UserService;

    @RequestMapping(value={"/", "/signin"})
    public String signin() {
        return "signin";
    }

    @RequestMapping(value="/signup", method=RequestMethod.GET)
    public SignupForm signupForm(WebRequest request) {
        Connection<?> connection = ProviderSignInUtils.getConnection(request);
        if (connection != null) {
            return SignupForm.fromProviderUser(connection.fetchUserProfile());
        } else {
            return new SignupForm();
        }
    }

    @RequestMapping(value="/signup", method=RequestMethod.POST)
    public String signup(@Valid SignupForm form, BindingResult formBinding, WebRequest request) {
        if (formBinding.hasErrors()) {
            return null;
        }
        User user = createUser(form, formBinding);
        if (user != null) {
            SignInUtils.signin(user.getUsername());
            ProviderSignInUtils.handlePostSignUp(user.getUsername(), request);
            return "redirect:/home";
        }
        return null;
    }

    // Internal helpers
    private User createUser(SignupForm form, BindingResult formBinding) {
        User user = new User();
        user.setUsername(form.getUsername());
        user.setPassword(form.getPassword());

        UserProfile userProfile = new UserProfile();
        userProfile.setFirstName(form.getFirstName());
        userProfile.setLastName(form.getLastName());

        user.setUserProfile(userProfile);

        Role role = new Role();
        role.setName("ROLE_USER");

        user.getRoles().add(role);

        UserService.addUser(user);

        return user;
    }
}

弹簧安全.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-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

    <http pattern="/resources/css/**" security="none"/>
    <http pattern="/resources/images/**" security="none"/>
    <http pattern="/resources/scripts/**" security="none"/>

    <http use-expressions="true" access-denied-page="/accessDenied.jsp" >
        <form-login login-page="/signin" default-target-url="/home" login-processing-url="/signin/authenticate" authentication-failure-url="/signin?error=bad_credentials"/>        
        <logout logout-success-url="/signin" />
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/group/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/group" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/home" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/**" access="permitAll" />
        <intercept-url pattern="/auth/**" access="permitAll" />
        <intercept-url pattern="/disconnect/facebook" access="permitAll" />
        <remember-me user-service-ref="userDetailsService" />

    <!--<session-management invalid-session-url="/invalidsession.jsp">
            <concurrency-control max-sessions="1"
                error-if-maximum-exceeded="true" />
        </session-management>-->

        <!--  Spring Social Security authentication filter -->
        <custom-filter ref="socialAuthenticationFilter" before="PRE_AUTH_FILTER" />
    </http>

    <beans:bean id="customEncoder" class="com.youthministry.security.CustomPasswordEncoder" />
    <beans:bean id="customUserService"
        class="com.youthministry.security.CustomUserDetailService" >
    </beans:bean>

    <authentication-manager alias="authenticationManager" >
        <authentication-provider user-service-ref="customUserService">
            <password-encoder ref="customEncoder" />
        </authentication-provider>
        <!-- Spring Social Security authentication provider -->
        <authentication-provider ref="socialAuthenticationProvider" />
    </authentication-manager>

    <jdbc-user-service id="userDetailsService" 
                    data-source-ref="dataSource" 
                    users-by-username-query="select username, password, true from User where username = ?"
                    authorities-by-username-query="select u.username username, r.name authority from user_roles u_roles, user u, roles r where u.username = ?"/>

    <beans:bean id="textEncryptor" class="org.springframework.security.crypto.encrypt.Encryptors"
        factory-method="noOpText" />

    <beans:bean id="passwordEncoder" class="org.springframework.security.crypto.password.NoOpPasswordEncoder"
        factory-method="getInstance" />

</beans:beans>

如果可能需要任何其他文件来帮助让我知道。否则这里是 github repo 的链接。

http://github.com/dmcquillan314/YouthMinistryHibernate.git

在此先感谢您提供的任何帮助,我对 spring 仍然很陌生,并试图找出有关初始 spring-security 配置的一些问题。也欢迎对 github 项目提出任何意见。

4

1 回答 1

2

我认为问题在于SignInUtils.signin()您将身份验证令牌放入不包含任何内容的安全上下文中GrantedAuthority(的第三个参数new UsernamePasswordAuthenticationToken()为空),然后将请求重定向到/home配置为需要ROLE_USER权限的 URL ( )。

于 2013-03-16T12:31:22.127 回答