Spring Security:通过从DB提供rolename重定向到页面

时间:2015-01-26 15:19:10

标签: spring hibernate spring-security

我有3个用户角色访问权限,ROLE_ADMIN,ROLE_SUPER_ADMIN,ROLE_USER。(角色可能会在未来增加。所以硬编码角色根本不是强制性的)

我的security_servlet.xml就是这样的

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

    <form-login login-page="/login"
        authentication-failure-url="/accessdenied" />
    <logout logout-success-url="/logout" />
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <!-- <user-service> <user name="rohit" password="rohit" authorities="ROLE_ADMIN" 
            /> <user name="ronnie" password="ronnie" authorities="ROLE_USER" /> </user-service> -->

        <jdbc-user-service data-source-ref="dataSource"
            users-by-username-query="select username, password, active from users where username=?"
            authorities-by-username-query="select us.username, ur.authority from users us, user_roles ur 
    where us.user_id = ur.user_id and us.username =?  " />
    </authentication-provider>
</authentication-manager>

登录后,它会重定向到&#34; /&#34;。我想要的是角色是&#34; ROLE_ADMIN&#34;然后它应该登陆管理员默认页面,如&#34; / admin / profile&#34;,如果角色是&#34; ROLE_USER&#34;然后&#34; / user / profile&#34;

我使用了default-target-url,但它不适用于我。

2 个答案:

答案 0 :(得分:0)

您可以使用Spring MVC控制器将用户重定向到所需的页面:

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains("ROLE_ADMIN"))
            return "redirect:/admin/profile";
        if (roles.contains("ROLE_USER"))
            return "redirect:/user/profile";
        // and so on
    }

}

答案 1 :(得分:0)

像这样更新spring security的成功处理程序

<form-login login-page="/login"
        authentication-failure-url="/accessdenied"  authentication-success-handler-ref="roleBasedRedirect"/>

添加roleBasedRedirect服务bean     

现在你可以像下面这样做了

public class RoleBasedRedirectService extends SavedRequestAwareAuthenticationSuccessHandler{



    @Override
    protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
            for(GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities())
            {
                if(authority.toString().equals("ROLE_ADMIN"))
                    return "/admin/profile/";
                else if(authority.toString().equals("ROLE_USER"))
                    return "/user/profile/";
            }
            return "";
    }

}