Spring Security条件default-target-url [英] Spring Security conditional default-target-url
问题描述
我注意到有几个问题询问了这个话题。我查看了它们,我无法将它们应用到我特定的Spring设置中。我想根据用户的角色将我的登录重定向配置为有条件的。这是我到目前为止:
I've noticed that there are a couple of questions asking about this topic. I looked through them and I was unable to apply them to my specific Spring setup. I would like to configure my login redirect to be conditional, based on the user's role. This is what I have so far:
<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>
我想这个问题可能与我正在尝试的内容处于同一行。有人知道如何申请吗?
I thought this question might be in the same line as what I'm trying to do. Anyone know how I can apply it though?
编辑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
目前我没有像这样的类公共类测试实现AuthenticationSuccessHandler {}
,如此示例。
推荐答案
我测试了代码并且它有效,其中没有火箭科学
I have tested the code and it works, there's no rocket science in it
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"/>
更新如果你想使用默认 - target-url
方法,它同样有效,但会在用户首次访问登录页面时触发:
update if you want to use default-target-url
approach, it will work equally well, but will be triggered when your user first accesses the login page:
< 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");
}
}
这篇关于Spring Security条件default-target-url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!