gpt4 book ai didi

java - Spring 安全: redirect logged user depending on some conditions

转载 作者:行者123 更新时间:2023-12-02 03:46:16 24 4
gpt4 key购买 nike

我是 Spring Security 3 的新手。

我想做以下事情:当用户登录时,我希望系统验证用户是否确认了其电子邮件地址,以及用户是否配置了其帐户配置文件。

我不知 Prop 体该怎么做。

我尝试过这个:

<http use-expressions="true" auto-config="true">
<intercept-url ... />
...
<custom-filter after="SECURITY_CONTEXT_FILTER" ref="usrFilter" />
...
</http>

<b:bean id="usrFilter"
class="com.zxxztech.zecure.security.MyAuthenticationFilter">
<b:property name="authenticationManager" ref="authenticationManager" />
<b:property name="failureHandler">
<b:bean
class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
<b:property name="exceptionMappings">
<b:map>
<b:entry key="org.springframework.security.authentication.DisabledException" value="/disabled.htm" />
</b:map>
</b:property>
</b:bean>
</b:property>
</b:bean>

这是我的过滤器:

public class MyAuthenticationFilter extends GenericFilterBean {
...
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication != null) {
Usuario usuario=(Usuario) authentication.getPrincipal();
if (usuario.getActivationKey()!=null) {
((HttpServletResponse) response).sendRedirect("/activacion");
return;
} else if (authentication.getAuthorities().contains(AppRole.NUEVO_USUARIO)) {
((HttpServletResponse)response).sendRedirect("/configuracion_modelo");
return;
}
}

chain.doFilter(request, response);
}

...
}

但是,当我逐步调试应用程序并登录时,过滤器会无限期地调用,就像在循环中一样。

正确的做法是怎样的?

最佳答案

您需要在重定向到的 URL 上继续过滤器链。例如:

import org.springframework.security.web.util.UrlUtils;

public class MyAuthenticationFilter extends GenericFilterBean {
...
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication != null) {
String currentUrl = UrlUtils.buildRequestUrl((HttpServletRequest) request);
Usuario usuario=(Usuario) authentication.getPrincipal();
if("/activacion".equals(currentUrl) || "/configuracion_modelo".equals(currentUrl)) {
chain.doFilter(request, response);
return;
} else if (usuario.getActivationKey()!=null) {
((HttpServletResponse) response).sendRedirect("/activacion");
return;
} else if (authentication.getAuthorities().contains(AppRole.NUEVO_USUARIO)) {
((HttpServletResponse)response).sendRedirect("/configuracion_modelo");
return;
}
}

chain.doFilter(request, response);
}

...
}

关于java - Spring 安全: redirect logged user depending on some conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19547722/

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