有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法从spring安全会话获取活动用户列表

我想从spring security获取活动用户列表。由于我是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;
}

这是我的应用程序上下文。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>

这是我的网站。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>

请帮助我,我的代码有什么问题,或者如何获取活动用户列表。我对spring security和java非常陌生。谢谢你抽出时间


共 (1) 个答案

  1. # 1 楼答案

    查看您是否有或需要以下会话身份验证策略

    <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>