gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:12:24 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以重新定义 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());
}

关于java - 认证后转到特定的jsp页面(spring security),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32199231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com