gpt4 book ai didi

java - Spring Security 有条件的 default-target-url

转载 作者:IT老高 更新时间:2023-10-28 13:56:29 26 4
gpt4 key购买 nike

我注意到有几个关于此主题的问题。我查看了它们,但无法将它们应用于我的特定 Spring 设置。我想根据用户的角色将我的登录重定向配置为有条件的。这是我目前所拥有的:

<http auto-config="true" use-expressions="true">
<custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/>
<access-denied-handler ref="accessDeniedHandler"/>
<form-login
login-page="/login"
default-target-url="/admin/index"
authentication-failure-url="/index?error=true"
/>
<logout logout-success-url="/index" invalidate-session="true"/>
</http>

我以为 this question可能与我正在尝试做的事情在同一行。有谁知道我如何应用它?

编辑 1

<bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
</bean>
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/login.jsp"/>
</bean>

编辑 2

目前我没有像 public class Test implements AuthenticationSuccessHandler {} 这样的类,如 this example 所示.

最佳答案

我已经测试了代码并且它可以工作,其中没有火箭科学

public class MySuccessHandler implements AuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")){
response.sendRedirect("/Admin.html");
return;
}
response.sendRedirect("/User.html");
}
}

您的安全环境的变化:

<bean id="mySuccessHandler" class="my.domain.MySuccessHandler">
</bean>

<security:form-login ... authentication-success-handler-ref="mySuccessHandler"/>

更新如果你想使用 default-target-url方法,它同样可以正常工作,但会在您的用户第一次访问登录页面时触发:

<security:form-login default-target-url="/welcome.htm" />

@Controller
public class WelcomeController {
@RequestMapping(value = "/welcome.htm")
protected View welcome() {

Set<String> roles = AuthorityUtils
.authorityListToSet(SecurityContextHolder.getContext()
.getAuthentication().getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
return new RedirectView("Admin.htm");
}
return new RedirectView("User.htm");
}
}

关于java - Spring Security 有条件的 default-target-url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11930980/

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