根据struts2的角色确定目标URL

时间:2012-03-07 09:29:15

标签: authentication struts2 spring-security authorization j-security-check

我是struts和spring security的新手。 任何人都可以帮我弄清楚如何将不同角色的不同用户重定向到不同的网址?换句话说,如何使用动作控制器根据struts2中的用户角色提供确定目标URL?

我发现了以下问题determine target url based on roles in spring security 3.1,但我无法弄清楚如何配置操作。

我尝试了以下设置,但它不起作用:

security.xml文件

 <form-login login-page="/login" authentication-failure-url="/login?error=true" login-processing-url="/j_security_check" default-target-url="/default"/>

struts.xml中

<action name="default" class="com.moblab.webapp.action.RoleRedirectAction" method="defaultAfterLogin"/>

RoleRedirectAction.java

package com.moblab.webapp.action;
import javax.servlet.http.HttpServletRequest;
public class RoleRedirectAction extends BaseAction{

public String defaultAfterLogin(HttpServletRequest request) {
    if (request.isUserInRole("ROLE_ADMIN")) {
        return "redirect:/<url>";
    }
    return "redirect:/<url>";
}
}

非常感谢。

编辑1 我还尝试了以下注释

 @Action(value="/default",results={@Result(name="success",location="/querySessions")})

编辑2 我的最终解决方案如下所示。我不确定它是否是最佳方法,但它确实有效:

public class StartPageRouter extends SimpleUrlAuthenticationSuccessHandler {


@Autowired
private UserService userService;

protected final Logger logger = Logger.getLogger(this.getClass());
private RequestCache requestCache = new HttpSessionRequestCache();

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Authentication authentication) throws IOException, ServletException {


    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

    //default path for ROLE_USER
    String redirectPath = <url>;

    if (authorities != null && !authorities.isEmpty()) {

        Set<String> roles = getUserRoles(authorities);

        if (roles.contains("ROLE_ADMIN"))
            redirectPath = <url>;
        else if (roles.contains("ROLE_INSTRUCTOR"))
            redirectPath = <url>;
    }

    getRedirectStrategy().sendRedirect(request, response, redirectPath);
}

public void setRequestCache(RequestCache requestCache) {
    this.requestCache = requestCache;
}

private Set<String> getUserRoles(Collection<? extends GrantedAuthority> authorities) {

    Set<String> userRoles = new HashSet<String>();

    for (GrantedAuthority authority : authorities) {
        userRoles.add(authority.getAuthority());
    }
    return userRoles;
}
}

编辑3 这里有更好的解决方案:

http://oajamfibia.wordpress.com/2011/07/07/role-based-login-redirect/#comment-12

1 个答案:

答案 0 :(得分:2)

假设您要将用户重定向到不同的起始页面,具体取决于他们分配的角色,那么您可以尝试这样做。请注意,我在Struts之外做了所有这些。

首先创建自己的类,扩展Springs SimpleUrlAuthenticationSuccessHandler并覆盖onAuthenticationSuccess()方法。实际的重定向是在onAuthenticationSuccess()方法中通过行getRedirectStrategy()执行的.sendRedirect(request,response,);

所以你需要的是一种替代你自己的网址的方法。

所以,例如我有

package com.blackbox.x.web.security;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import com.blackbox.x.entities.UserDTO;
import com.blackbox.x.services.UserService;


public class StartPageRouter extends SimpleUrlAuthenticationSuccessHandler {


 @Autowired
 UserService userService;

 @Autowired
 LoginRouter router;


 protected final Logger logger = Logger.getLogger(this.getClass());
 private RequestCache requestCache = new HttpSessionRequestCache();

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication) throws IOException,
        ServletException {


    requestCache.removeRequest(request, response);

    User user = (User) authentication.getPrincipal();
    UserDTO userDTO = userService.find(user.getUsername());

    getRedirectStrategy().sendRedirect(request, response, router.route(userDTO));
}

public void  setRequestCache(RequestCache requestCache) {
            this.requestCache = requestCache;
        }
}

其中LoginRouter是我自己的类,它接收登录用户,并从指定的角色确定用户应该定向到哪个URL。

然后,您可以将Spring Security配置为使用

来使用您的版本
authentication-success-handler-ref="customTargetUrlResolver"/> 

<beans:bean id="customTargetUrlResolver" class="com.blackbox.x.web.security.StartPageRouter"/>

在安全上下文xml文件中。