简体   繁体   English

无法从Spring Security会话获取活动用户列表

[英]Can't get active user list from spring security session

I want to get active user list from spring security. 我想从Spring Security获取活跃的用户列表。 As I am new to spring security, I get some reference codes by googling, the following codes are to get user list.. 由于我是Spring Security的新手,因此通过谷歌搜索获得了一些参考代码,以下代码用于获取用户列表。

 @Autowired
 @Qualifier("sessionRegistry")
 private SessionRegistryImpl sessionRegistry;


@RequestMapping(value = "/authenticate", method = {RequestMethod.POST },consumes ="application/json",produces = "application/json")
public @ResponseBody LoginResponse authentication(@RequestBody User user, HttpServletRequest request) throws AuthenticationException {

  String userName=user.getUsername();
  String password=user.getPassword();

  List<Object> principals = sessionRegistry.getAllPrincipals();

  List<User> usersNamesList = new ArrayList<User>();

  for (Object principal: principals) {
      if (principal instanceof User) {
          usersNamesList.add((User) principal);
      }
  }
  Authentication authenticationToken = new UsernamePasswordAuthenticationToken(
          userName, password);
  Authentication authentication = authenticationManager
          .authenticate(authenticationToken);


  SecurityContext securityContext = SecurityContextHolder
          .getContext();

  securityContext.setAuthentication(authentication);

  HttpSession session = request.getSession(true);
  session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
  LoginResponse response = new LoginResponse("success", session.getId());

  return response;
}

And here is my application-context.xml 这是我的application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans  
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
                  http://www.springframework.org/schema/security 
                  http://www.springframework.org/schema/security/spring-security.xsd">


<!-- Get a basic Spring Security provided form based login infra -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/index" access="permitAll" />
    <intercept-url pattern="/index.jsp" access="permitAll" />
    <intercept-url pattern="/app/**" access="permitAll" />
    <intercept-url pattern="/simplemessages/**" access="permitAll" />
    <intercept-url pattern="/topic/**" access="permitAll" />
    <intercept-url pattern="/topic/simplemessages" access="permitAll" />
    <intercept-url pattern="/resources/**" access="permitAll" />
    <intercept-url pattern="/login" access="permitAll" />
    <intercept-url pattern="/loginPage" access="permitAll" />
    <!-- Requests to secured pages need to be authenticated and authorized -->
    <intercept-url pattern="/secured/*"
        access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />
    <!-- Define the security form login and logout pages/urls -->
    <form-login login-processing-url="/login" login-page="/loginPage"
        username-parameter="username" password-parameter="password"
        default-target-url="/secured/basicWebsockets"
        authentication-failure-url="/loginPage?auth=fail" />

    <logout invalidate-session="true" logout-url="/logout"
        logout-success-url="/logoutPage" />
    <session-management session-fixation-protection="migrateSession" session-authentication-error-url="/login.html?authFailed=true"> 
        <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" expired-url="/login.html" session-registry-alias="sessionRegistry"  session-authentication-strategy-ref="sas"/>
    </session-management>
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <user-service>
            <user name="john" password="doe" authorities="ROLE_USER" />
            <user name="sunit" password="katkar" authorities="ROLE_USER" />
            <user name="admin" password="admin" authorities="ROLE_USER,ROLE_ADMIN" />
        </user-service>
    </authentication-provider>
</authentication-manager>

Here is my web.xml 这是我的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.4">
<display-name>Spring Web MVC Application</display-name>
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <async-supported>true</async-supported>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
     <listener-class>
      org.springframework.security.web.session.HttpSessionEventPublisher
    </listener-class>
 </listener> 

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Please help me, what's wrong with my codes or how to get active user list. 请帮助我,我的代码有什么问题或如何获取有效的用户列表。 I am very new to spring-security and java . 我对spring-security和java非常java Thanks for your time. 谢谢你的时间。

See if you have or need Session Authenticatin Strategy as below 如下所示,查看您是否具有会话身份验证策略

<http>
  <session-management session-authentication-strategy-ref="sas"/>
</http>

<beans:bean id="sas" class="org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy">
  <beans:constructor-arg>
    <beans:list>
      <beans:bean class="org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy">
        <beans:constructor-arg ref="sessionRegistry"/>
        <beans:property name="maximumSessions" value="1" />
        <beans:property name="exceptionIfMaximumExceeded" value="true" />
      </beans:bean>
      <beans:bean class="org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy">
      </beans:bean>
      <beans:bean class="org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy">
        <beans:constructor-arg ref="sessionRegistry"/>
      </beans:bean>
    </beans:list>
  </beans:constructor-arg>
</beans:bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM