我是 Spring Security 3 的新手。我正在使用角色让用户登录。
我想在用户被授权进入应用程序后添加一些会话值。也许我需要一些过滤器,以便它重定向到我添加一些会话值的方法。我已经配置了我的 security.xml 文件,但我不确定我是否在做正确的事情。这个方向的任何例子都会有所帮助。我应该使用哪个过滤器类?我应该如何配置 security.xml 文件?
<custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>
<beans:bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<beans:property name="filterProcessesUrl" value="/j_spring_security_check" />
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="authenticationSuccessHandler" ref="successHandler" />
</beans:bean>
<beans:bean id="successHandler" class="org.dfci.sparks.datarequest.security.CustomAuthorizationFilter"/>
我的过滤器类方法我需要添加一些会话值。
public class CustomAuthorizationFilter 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_USER")) {
request.getSession().setAttribute("myVale", "myvalue");
}
}
}
编辑代码
我修改了我的 security.xml 文件和类文件
<custom-filter ref="authenticationFilter" after="FORM_LOGIN_FILTER "/>
public class CustomAuthorizationFilter extends GenericFilterBean {
/*
* ServletRequestAttributes attr = (ServletRequestAttributes)
* RequestContextHolder.currentRequestAttributes(); HttpSession
* session=attr.getRequest().getSession(true);
*/
@Autowired
private UserService userService;
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession(true);
Authentication authentication = SecurityContextHolder
.getContext().getAuthentication();
Set<String> roles = AuthorityUtils
.authorityListToSet(authentication.getAuthorities());
User user = null;
if (true) {
session.setAttribute("Flag", "Y");
}
}
} catch (IOException ex) {
throw ex;
}
}
}
它调用每个 URL。当用户通过身份验证时,是否只调用一次过滤方法?