认证后转到特定的jsp页面(spring security)

Posted

技术标签:

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

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

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

【问题讨论】:

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

以上是关于认证后转到特定的jsp页面(spring security)的主要内容,如果未能解决你的问题,请参考以下文章

服务端通知浏览器3秒后转到目标页面

a标记 跳转到 另一页面特定位置

Spring Security自定义登录页面

asp中session的问题

使用带有 Laravel Vue 应用程序的 vue-router,如果我在登录后转到基本 URL,它会显示 404

html按下单击弹出确认窗口确认后转到链接