【问题标题】:Go to a specific jsp page after authentication (spring security)认证后转到特定的jsp页面(spring security)
【发布时间】:2015-11-18 21:01:26
【问题描述】:

我的应用程序中有 3 种类型的用户,每个用户都有自己的 jsp 页面。我希望在身份验证后,每个用户都被重定向到他的“自己的”页面,这怎么做?

我正在使用 Spring Security,我是新手。

【问题讨论】:

  • '每个用户都有自己的 jsp 页面'对我来说没有任何意义。每个用户不能有不同的页面。您需要一个profile 页面,您可以在其中显示有关已登录用户的信息。
  • 我不鼓励您提出的解决方案,因为您需要为应用程序的每个新用户创建一个新的 jsp 页面并更新您的网络应用程序。试试@IgnazioC 提出的建议
  • 为什么没有一个固定的页面,但是会重定向到特定的页面?
  • 谢谢你们的回复。我没有从头开始应用程序,我只是添加我的部分,我只有 3 种类型的用户:A、B 和 C(用户数量稳定)你的答案很有趣 @Taliman 但我更喜欢重新编辑是在身份验证时自动进行的。
  • 用户类型稳定*

标签: java spring jsp spring-mvc spring-security


【解决方案1】:

您可以重新定义 Spring Security 身份验证成功处理程序

创建一个实现 AuthenticationSuccessHandler 的类:

public class RoleBasedAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//Store the role and destination url relationship 
private static Map<String, String>  ROLE_URL_MAP    = new HashMap<String, String>(); 
static {
    ROLE_URL_MAP.put("ROLE_AUDIT", "/private/auditindex.do");
    ROLE_URL_MAP.put("ROLE_USER", "/private/userindex.do");
    ROLE_URL_MAP.put("ROLE_ADMIN", "/private/adminindex.do");
}

private static String               DEFAULT_URL     = "/private/home.do";

/**
 * {@inheritDoc}
 */
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

    if (authentication.getPrincipal() instanceof UserDetails) {
        //obtain the userDetails
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //rediret to destination url
        response.sendRedirect(request.getContextPath() + getTargetUrl(userDetails));
    } else {
        //rediret to default url
        response.sendRedirect(request.getContextPath() + DEFAULT_URL);
    }

}

/** 
 * get de target Url for roluser
 * @param userDetails userDetails
 * @return target url after login
 */
public static String getTargetUrl(UserDetails userDetails) {
    String role = userDetails.getAuthorities().isEmpty() ? null : userDetails.getAuthorities().toArray()[0].toString();
    String targetUrl = ROLE_URL_MAP.get(role);
    if (targetUrl != null) {
        return targetUrl;
    } else {
        return DEFAULT_URL;
    }
}
}

如果你使用 xml-confi,你定义你的 bean:

<beans:bean id="redirectRoleStrategy" class="xxx.xxx.RoleBasedAuthenticationSuccessHandler"/>

<security:form-login authentication-success-handler-ref="redirectRoleStrategy">

但是如果你使用 java-config 包含在 WebSecurityConfigurerAdapter

 @Override
protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().successHandler(new RoleBasedAuthenticationSuccessHandler());
}

【讨论】:

  • 非常感谢 Jorge Jiménez Barra,我会尽快测试并给您反馈。
猜你喜欢
  • 1970-01-01
  • 2018-02-10
  • 2020-02-26
  • 2014-07-21
  • 2016-05-16
  • 2022-09-23
  • 2021-06-27
  • 1970-01-01
  • 2021-08-22
相关资源
最近更新 更多