Spring安全性 - 自定义userDetailsS​​ervice实现未被调用

时间:2015-12-04 17:04:35

标签: java spring-mvc spring-security

尝试使用自定义userDetailsS​​ervice学习spring安全性并面对以下问题

当访问受限制的页面(/ admin或/ user)时,弹出安全性启动并显示登录页面 但是在使用正确的用户名和密码提交登录页面后,在调用我的自定义userDetailsS​​ervice实现中的loadUserByUsername方法之前,会直接显示访问被拒绝页面。

在日志中,只有org.springframework.security.access.AccessDeniedException例外 - 访问受限页面时,没有其他例外。

代码

@Controller
public class TestController {

    @RequestMapping("/home")
    public String getHomePage() {
        return "home";
    }


    @RequestMapping(value="/user")
    public String getUserPage() {
        return "user";
    }

    @RequestMapping(value="/admin")
    public String getAdminPage() {
        return "admin";
    }
}

安全配置:

<http auto-config="true"  use-expressions="true">
        <intercept-url pattern="/" access="permitAll"/>
        <intercept-url pattern="/login" access="permitAll"/>
        <intercept-url pattern="/logout" access="permitAll"/>
        <intercept-url pattern="/denied" access="hasRole('ROLE_USER')"/>
        <intercept-url pattern="/user" access="hasRole('ROLE_USER')"/>
        <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')"/>

        <form-login login-page="/login"
            username-parameter="tmp_usrnm"
            password-parameter="tmp_pwd" 
            authentication-failure-url="/login/failure" 
            default-target-url="/abcd"/>

        <access-denied-handler error-page="/denied"/>

        <logout invalidate-session="true" 
            logout-success-url="/logout/success" 
            logout-url="/logout"/>
    </http>

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

    <beans:bean id="customUserDetailsService" class="com.krishnan.balaji.mc.service.CustomUserDetailsService">
        <beans:property name="userRepository">
            <beans:bean class="com.krishnan.balaji.mc.repos.UserRepositoryImpl"></beans:bean>   
        </beans:property>
    </beans:bean>

登录表单:

<!--<form class="login-form" action=<c:url value="j_spring_security_check"/> method="post" >-->
<form action=<c:url value="/login"/> method="post" >
            <input id="j_username" name="tmp_usrnm" size="20" maxlength="50" type="text"/>
            <input id="j_password" name="tmp_pwd" size="20" maxlength="50" type="password"/>
            <p><input type="submit" value="Login"/></p>
</form> 

控制器用于提供登录/注销/访问被拒绝的页面

@Controller
public class UserAccessController {

    @RequestMapping("/login")
    public String login(Model model, @RequestParam(required=false) String message) {
        model.addAttribute("message", message);
        System.out.println("serving login page");
        return "access/login";
    }

    @RequestMapping(value = "/denied")
    public String denied() {
        System.out.println("serving access denied page");
        return "access/denied";
    }

    @RequestMapping(value = "/login/failure")
    public String loginFailure() {
        System.out.println("serving failed login page");
        String message = "Login Failure!";
        return "redirect:/login?message="+message;
    }

    @RequestMapping(value = "/logout/success")
    public String logoutSuccess() {
        System.out.println("serving logout page");
        String message = "Logout Success!";
        return "redirect:/login?message="+message;
    }
}

CustomUserDetailsS​​ervice

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private UserRepository userRepository;;

    @Transactional(readOnly = true)
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        System.out.println("loadUserByUsername called");
        try {
            com.krishnan.balaji.mc.model.User domainUser = userRepository
                    .getUserByUserName(username);

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;

            return new User(domainUser.getUsername(), domainUser.getPassword()
                    .toLowerCase(), enabled, accountNonExpired,
                    credentialsNonExpired, accountNonLocked,
                    getAuthorities(domainUser.getRole().getRole()));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Integer role) {
        List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
        return authList;
    }

    public List<String> getRoles(Integer role) {
        List<String> roles = new ArrayList<String>();

        if (role.intValue() == 1) {
            roles.add("ROLE_USER");
            roles.add("ROLE_ADMIN");

        } else if (role.intValue() == 2) {
            roles.add("ROLE_USER");
        }

        return roles;
    }

    public static List<GrantedAuthority> getGrantedAuthorities(
            List<String> roles) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
        return authorities;
    }

    public UserRepository getUserRepository() {
        return userRepository;
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

}

1 个答案:

答案 0 :(得分:0)

http的Spring Security配置中,您应该更改以下内容:

default-target-url="/abcd"

类似

default-target-url="/"

或您定义的任何其他内容。

  • default-target-url在登录过程succeeds时定义默认的去向。
  • 确保从最具体到最通用的
  • 定义所有必要的intercept-url