Vid*_*ian 4 spring spring-security
我有一个使用Spring 4.0和Security 3.2的应用程序构建,我想实现会话并发,但它似乎不起作用.安全性的所有其他方面都运行得很好.这是我的xml配置:
首先在我的web.xml中:
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
然后在我的security.xml中
<security:http auto-config="false"
use-expressions="true"
authentication-manager-ref="authManager"
access-decision-manager-ref="webAccessDecisionManager"
entry-point-ref="authenticationEntryPoint">
<security:intercept-url pattern="/agent/**" access="hasAnyRole('ROLE_AGENT')" />
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/public/**" access="permitAll" />
<security:intercept-url pattern="/**" access="permitAll" />
<security:session-management session-authentication-strategy-ref="sas"
invalid-session-url="/public/login.xhtml"/>
<security:logout logout-success-url="/public/login.xhtml"
invalidate-session="true"
delete-cookies="true"/>
<security:expression-handler ref="webExpressionHandler"/>
<security:custom-filter position="FORM_LOGIN_FILTER" ref="myAuthFilter" />
<security:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
</security:http>
Run Code Online (Sandbox Code Playgroud)
和
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg index="0" value="/public/login.xhtml" />
</bean>
<bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
p:defaultFailureUrl="/public/login.xhtml" />
<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
<bean id="concurrencyFilter" class="org.springframework.security.web.session.ConcurrentSessionFilter">
<constructor-arg index="0" ref="sessionRegistry"/>
<constructor-arg index="1" value="/session-expired.htm"/>
</bean>
<bean id="myAuthFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="sessionAuthenticationStrategy" ref="sas" />
<property name="authenticationManager" ref="authManager" />
<property name="authenticationFailureHandler" ref="customAuthenticationFailureHandler"/>
</bean>
<bean id="sas" class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg name="sessionRegistry" ref="sessionRegistry" />
<property name="maximumSessions" value="1" />
<property name="exceptionIfMaximumExceeded" value="true" />
</bean>
<bean id="authManager" class="org.springframework.security.authentication.ProviderManager">
<property name="providers">
<list>
<ref bean="myCompLdapAuthProvider"/>
<ref bean="myCompDBAuthProvider"/>
</list>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
我的UserDetails实现hashCode()一个equals(),并且所有这些并发会话限制不起作用.经过一点调试后,我发现在sessionRegistry中找不到我的会话,我猜这是主要原因,但我不知道为什么!?
知道我在这里做错了什么吗?
PS我的调试日志中有这样的记录:
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 2 of 11 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 3 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 5 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
(FilterChainProxy.java:337) - /resources/images/icons/connection_on.gif at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
(AnonymousAuthenticationFilter.java:107) - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@96cf68e: Principal: MyUserDetails [username=adrian.videanu, dn=org.springframework.ldap.core.DirContextAdapter: dn=cn=Adrian Videanu,ou=IT,ou=Organization .....
Run Code Online (Sandbox Code Playgroud)
所以调用过滤器......
更新
我可以看到会话创建事件已发布,因为我在日志中有这一行:
(HttpSessionEventPublisher.java:66) - Publishing event: org.springframework.security.web.session.HttpSessionCreatedEvent[source=org.apache.catalina.session.StandardSessionFacade@3827a0aa]
Run Code Online (Sandbox Code Playgroud)
但我从未尝试过SessionRegistryImpl中的registerNewSession方法.当我最初打开登录页面时调用HttpSessionEventPublisher,因为我想在创建会话时,但是在我输入凭据并推送提交后,HttpSessionEventPublisher不再被调用.
更新2
作为测试,我将SessionRegistryImpl注入到我的一个bean中,以便尝试访问它的一些方法:
@Named
@Scope("view")
public class UserDashboardMB implements Serializable {
private static final long serialVersionUID = 1L;
@Inject
private SessionRegistry sessionRegistry;
public void init(){
System.out.println("-- START INIT -- ");
List<Object> principals = sessionRegistry.getAllPrincipals();
System.out.println("Principals = "+principals);
for (Object p:principals){
System.out.println("Principal = "+p);
}
System.out.println("-- STOP INIT -- ");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
INFO: - START INIT -
INFO:Principals = []
INFO: - STOP INIT -
所以,那里没有任何东西填充.
更新3
我用Serge提供的那个替换了"sas"豆,但它似乎仍然没有用.我再次修改了调试器,我认为问题是在方法doFilter()上的类UsernamePasswordAuthenticationFilter上,我的请求都没有按照它应该处理.这是doFilter()的一部分:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!requiresAuthentication(request, response)) {
chain.doFilter(request, response);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Request is to process authentication");
}
Authentication authResult;
// rest of method here
}
Run Code Online (Sandbox Code Playgroud)
从我在调试器中看到的情况来看,我的请求似乎不需要auth和chain.doFilter(request,response); 被调用.
更新4
我想我发现了这个问题.过滤器未按预期运行,因为filterUrl参数不是正确的.正如我在文档中读到的那样:
默认情况下,此过滤器响应URL/j_spring_security_check.
但我的登录部分是使用JSF托管bean和操作实现的.现在,我的登录表单位于/public/login.xhtml,登录信息发布的网址是相同的.如果我把它设置为filterUrl我有问题,因为在初始表单渲染也被调用,我有一个无限循环,因为没有设置用户/密码.
知道如何克服这个问题吗?
这就是我的LoginManagedBean的样子:
@Named
@Scope("request")
public class LoginMB implements Serializable {
private static final long serialVersionUID = 1L;
@Autowired
@Qualifier("authManager")
private AuthenticationManager authenticationManager;
// setters and getters
public String login(){
FacesContext context = FacesContext.getCurrentInstance();
try {
Authentication request = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
// perform some extra logic here and return protected page
return "/agent/dashboard.xhtml?faces-redirect=true";
} catch (AuthenticationException e) {
e.printStackTrace();
logger.error("Auth Exception ->"+e.getMessage());
FacesMessage fm = new FacesMessage("Invalid user/password");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
context.addMessage(null, fm);
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
spring security 3.1和spring security 3.2之间在并发会话管理方面存在细微差别.
旧ConcurrentSessionControlStrategy的现在已被弃用.它检查是否超出了并发会话的数量,并检查SessionRegistry了将来使用的已注册会话.
它在3.2中被部分取代ConcurrentSessionControlAuthenticationStrategy.它有效地控制是否超过并发会话数但不再注册新会话(即使javadoc假装:我查看了源代码以了解它!)
如果现在委托给会话注册RegisterSessionAuthenticationStrategy!因此,对于会话并发到单词,您必须同时使用它们.和在3.2参考手册的例子中,有效地利用为豆sas一个CompositeSessionAuthenticationStrategy含有一个ConcurrentSessionControlAuthenticationStrategy,一个SessionFixationProtectionStrategy 和一个RegisterSessionAuthenticationStrategy!
为了整个工作,你只需sas要用以下内容替换你的bean:
<bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
<constructor-arg>
<list>
<bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
<constructor-arg ref="sessionRegistry"/>
<property name="maximumSessions" value="1" />
<property name="exceptionIfMaximumExceeded" value="true" />
</bean>
<bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
</bean>
<bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
<constructor-arg ref="sessionRegistry"/>
</bean>
</list>
</constructor-arg>
</bean>
Run Code Online (Sandbox Code Playgroud)
我终于设法解决了这个问题。问题是由于我在 spring 标准过滤器和自定义 jsf 登录表单之间进行了混合设置。正如 Serge 指出的那样,我在 xml conf 中只留下了“sas”bean,在我的 LoginMB 中,我手动并以编程方式调用了 SessionAuthenticationStrategy onAuthentication() 方法。现在我的 LoginMB 看起来像:
@Named
@Scope("request")
public class LoginMB implements Serializable {
@Autowired
@Qualifier("authManager")
private AuthenticationManager authenticationManager;
@Inject
@Qualifier("sas")
private SessionAuthenticationStrategy sessionAuthenticationStrategy;
public String login(){
FacesContext context = FacesContext.getCurrentInstance();
try {
Authentication authRequest = new UsernamePasswordAuthenticationToken(this.getUsername(), this.getPassword());
Authentication result = authenticationManager.authenticate(authRequest);
SecurityContextHolder.getContext().setAuthentication(result);
HttpServletRequest httpReq = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpServletResponse httpResp = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
sessionAuthenticationStrategy.onAuthentication(result, httpReq, httpResp);
// custom logic here
return "/agent/dashboard.xhtml?faces-redirect=true";
}catch(SessionAuthenticationException sae){
sae.printStackTrace();
logger.error("Auth Exception ->"+sae.getMessage());
String userMessage = "Session auth exception!";
if (sae.getMessage().compareTo("Maximum sessions of 1 for this principal exceeded") == 0){
userMessage = "Cannot login from more than 1 location.";
}
FacesMessage fm = new FacesMessage(userMessage);
fm.setSeverity(FacesMessage.SEVERITY_FATAL);
context.addMessage(null, fm);
}
catch (AuthenticationException e) {
e.printStackTrace();
logger.error("Auth Exception ->"+e.getMessage());
FacesMessage fm = new FacesMessage("Invalid user/password");
fm.setSeverity(FacesMessage.SEVERITY_FATAL);
context.addMessage(null, fm);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
现在会话已注册并且会话限制正在起作用。
| 归档时间: |
|
| 查看次数: |
11778 次 |
| 最近记录: |