Announcement Announcement Module
Collapse
No announcement yet.
Find all logged in users Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Find all logged in users

    Hi,

    I am trying to find all the logged in users at a given time. after reading following link http://static.springsource.org/sprin...ted-principals i tried following code but sessionRegistry.getAllPrincipals() method returns empty.

    Code:
    <security:http auto-config="true">
    	<security:intercept-url pattern="/**" filters="none" />
    	<security:session-management>
    		<security:concurrency-control session-registry alias="sessionRegistry" />
    	</security:session-management>
    </security:http>
    
    <bean id="testService" class="com.TestServiceImpl">
    	<property name="sessionRegistry" ref="sessionRegistry" />
    </bean>
    Am i doing something wrong here? by the way this a flex-java application, which is configured using spring-flex integration (i hope this being a flex application has nothing to do with this problem)

    Appriciate your help

    Thanks,
    Amila

  • #2
    Did you setup the required listener in your web.xml?

    Code:
    <listener>
        <listener-class>
          org.springframework.security.web.session.HttpSessionEventPublisher
        </listener-class>
      </listener>
    And did you also add the ConcurrentSessionFilter to the FilterChainProxy?

    Comment


    • #3
      I found a simmilar problem in following thread http://forum.springsource.org/showthread.php?t=99138. but i guess it is not solved.

      Comment


      • #4
        Hi skram,

        I did not add the listener and ConcurrentSessionFilter. let me add those and check again.

        Thanks a lot for your reply

        Comment


        • #5
          Originally posted by amiladomingo View Post
          Hi skram,

          I did not add the listener and ConcurrentSessionFilter. let me add those and check again.

          Thanks a lot for your reply
          Goodluck with it. Just looking at the documentation it looks like you'll need serious work with this one

          Comment


          • #6
            Check this thread for the solution:

            http://forum.springsource.org/showth...d=1#post336429

            Comment


            • #7
              Originally posted by skram View Post
              Check this thread for the solution:

              http://forum.springsource.org/showth...d=1#post336429
              Hi,

              Thanks for your well explained tutorial

              I tried it but couldn't customize it to get it working for my case. i think since my application configured with spring-flex (http://www.springsource.org/spring-flex), this might need a different configuration.

              I can't figure out how to configure the places i marked in red (where you have to specify a URL) since im using flex and i have no jsp (html) pages

              Code:
              <?xml version="1.0" encoding="UTF-8"?>
              <beans xmlns="http://www.springframework.org/schema/beans"
              	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                  xmlns:security="http://www.springframework.org/schema/security"
              	xmlns:p="http://www.springframework.org/schema/p" 
              	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-3.0.xsd">
              	
              	<!-- This is where we configure Spring-Security  -->
              	<security:http auto-config="false" use-expressions="true" 
                           access-denied-page="/krams/auth/denied" 
                           entry-point-ref="authenticationEntryPoint" >
              	
              		<security:intercept-url pattern="/krams/auth/login" access="permitAll"/>
              		<security:intercept-url pattern="/krams/main/admin" access="hasRole('ROLE_ADMIN')"/>
              		<security:intercept-url pattern="/krams/main/common" access="hasRole('ROLE_USER')"/>
              			
              		<security:logout 
              				invalidate-session="true" 
              				logout-success-url="/krams/auth/login" 
              				logout-url="/krams/auth/logout"/>
              	
              		<security:custom-filter ref="blacklistFilter" before="FILTER_SECURITY_INTERCEPTOR"/>
              		<security:custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER"/>
              		<security:custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
              		<security:session-management session-authentication-strategy-ref="sas"/>
              	</security:http>
              	
               	<!--  Custom filter to deny unwanted users even though registered -->
               	<bean id="blacklistFilter" class="org.krams.tutorial.filter.BlacklistFilter" />
               	
               	<!-- Custom filter for username and password. The real customization is done in the customAthenticationManager -->
               	<bean id="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
                		p:authenticationManager-ref="customAuthenticationManager"
                		p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
                		p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" 
                		p:sessionAuthenticationStrategy-ref="sas"/>
                		
              	<!-- Custom authentication manager. In order to authenticate, username and password must not be the same -->
              	<bean id="customAuthenticationManager" class="org.krams.tutorial.manager.CustomAuthenticationManager" />
               	
               	<!-- We just actually need to set the default failure url here -->
               	<bean id="customAuthenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
               		p:defaultFailureUrl="/krams/auth/login?error=true" />
               		
               	 <!-- We just actually need to set the default target url here -->
               	<bean id="customAuthenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler"
               		p:defaultTargetUrl="/krams/main/common" />
               	
               	<!-- The AuthenticationEntryPoint is responsible for redirecting the user to a particular page, like a login page,
               			whenever the server sends back a response requiring authentication -->
               	<!-- See Spring-Security Reference 5.4.1 for more info -->
               	<bean id="authenticationEntryPoint"  class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
              	 	p:loginFormUrl="/krams/auth/login"/>
              
              	<!-- The tag below has no use but Spring Security needs it to autowire the parent property of 
              			org.springframework.security.authentication.ProviderManager. Otherwise we get an error 
              			A probable bug. This is still under investigation-->
              	<security:authentication-manager/>
              	
              	<bean id="concurrencyFilter"
              	   class="org.springframework.security.web.session.ConcurrentSessionFilter">
              	  <property name="sessionRegistry" ref="sessionRegistry" />
              	  <property name="expiredUrl" value="/session-expired.htm" />
              	</bean>
              	
              	<bean id="sas" class=
              	 "org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
              	  <constructor-arg name="sessionRegistry" ref="sessionRegistry" />
              	  <property name="maximumSessions" value="1" />
              	</bean>
              
              	<bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />
              </beans>

              Comment


              • #8
                I think I've encountered a similar scenario for this using GWT (Maybe I'm gonna try making a sample Flex).

                For the following:
                Code:
                <security:intercept-url pattern="/krams/auth/login" access="permitAll"/>
                		<security:intercept-url pattern="/krams/main/admin" access="hasRole('ROLE_ADMIN')"/>
                		<security:intercept-url pattern="/krams/main/common" access="hasRole('ROLE_USER')"/>
                The way I designed my app is that the GWT is just basically a dumb view (a thin client). All rpc/ajax services are handled by the backend. The associated rpc urls are the ones I marked with intercept-url

                For the AuthenticationEntryPoint, FailureHandler, and SuccessHandler I had to implement these interfaces and return and HttpServletResponse (like OK, Unauthorized). The GWT app picks up this ServletResponse and I let it interpret what to do with those.

                For example, this is how my GWT handles the login (I have a GWT login form)
                Code:
                String username = form.getValueAsString("username");
                				String password = form.getValueAsString("password");
                LoginRequestCallback loginRequestCallback = new LoginRequestCallback();
                				loginRequestCallback.setEventBus(eventBus);
                				loginRequestCallback.setService(service);
                				loginRequestCallback.setUsername(username);
                				loginRequestCallback.setPassword(password);	
                RequestBuilder rb = new RequestBuilder(RequestBuilder.POST, loginUrl);
                				rb.setHeader("Content-Type", "application/x-www-form-urlencoded");
                				rb.setRequestData("j_username=" + URL.encode(username + "&j_password=" + URL.encode(password)));
                				
                				rb.setCallback(loginRequestCallback);	
                try {
                					rb.send();
                				} catch (RequestException re) {
                					Log.error("Exception in sending RequestBuilder: " + re.toString());
                				}

                Comment


                • #9
                  And here's LoginRequestCallback:
                  Code:
                  public void onResponseReceived(Request request, Response response) {
                  		if (response.getStatusCode() == 200) {
                  
                  Log.error("Login successful with authorization from Spring Security.");
                          	
                          	service.login(username, password, new AsyncCallback<HashMap<String, UserRoleDTO>>() 
                      				{
                      					@Override
                      					public void onFailure(Throwable caught) 
                      					{
                      						Log.error("Login failure from the async service: ", caught);
                      						SC.clearPrompt();
                      						SC.warn("Login error! Unable to login!");
                      					}
                  
                      					@Override
                      					public void onSuccess(HashMap<String, UserRoleDTO> result) 
                      					{
                      						Log.error("Login successful from the async service");
                      						SC.clearPrompt();
                      						eventBus.fireEvent(new LoginEvent(result));
                      						eventBus.fireEvent(new RoleChangeEvent(result));
                      					}						
                      				});
                  I know the code isn't pretty. I'm just copying and pasting on what I have currently

                  Come to think of it. I think this is the reason why I prefer JQuery than GWT
                  Last edited by skram; Dec 28th, 2010, 06:31 PM.

                  Comment


                  • #10
                    This is my AuthenticationEntryPoint:
                    Code:
                    public class CustomAuthorizedEntryPoint implements AuthenticationEntryPoint {
                    
                    	protected static Logger logger = Logger.getLogger("web");
                    	
                    	@Override
                    	public void commence(HttpServletRequest arg0, HttpServletResponse response,
                    			AuthenticationException arg2) throws IOException, ServletException {
                    
                    		 	HttpServletResponse httpResponse = (HttpServletResponse) response;
                    	        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
                    	}
                    
                    }
                    Here's my AuthenticationSuccessHandler:
                    Code:
                    public class CustomAuthenticationSuccessHandler implements
                    		AuthenticationSuccessHandler {
                    
                    	@Override
                    	public void onAuthenticationSuccess(HttpServletRequest arg0,
                    			HttpServletResponse response, Authentication arg2) throws IOException,
                    			ServletException {
                    		  HttpServletResponse httpResponse = (HttpServletResponse) response;
                    	        httpResponse.sendError(HttpServletResponse.SC_OK, "Authentication accepted");
                    	}
                    
                    }
                    Here's my AuthenticationFailureHandler:
                    Code:
                    public class CustomAuthenticationFailureHandler implements
                    		AuthenticationFailureHandler {
                    
                    	@Override
                    	public void onAuthenticationFailure(HttpServletRequest arg0,
                    			HttpServletResponse response, AuthenticationException arg2)
                    			throws IOException, ServletException {
                    		HttpServletResponse httpResponse = (HttpServletResponse) response;
                            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication not accepted");		
                    	}
                    
                    }
                    You no longer need to define any login/success/failure URL. Your Flex app should provide that. It just needs to interpret those ServletResponse codes and act accordingly. These entry point and handlers are all in the Java backend so I don't see any reason why you can't reuse it. Again, the login, success, and failure URL should be handled and shown by Flex.

                    I'm gonna try to make a sample demo this weekend.
                    Last edited by skram; Dec 28th, 2010, 06:39 PM.

                    Comment


                    • #11
                      Hey,

                      the reason i needed the logged in users was that i had a requirement to change the UI runtime if a admin goes and change the logged in user roles \ privileges.

                      i was able to the get the logged in flex clients with following code,

                      Code:
                      			
                      FlexClientManager flexClientManager = messageBroker.getFlexClientManager();
                      
                      String[] clientIDs = flexClientManager.getClientIds();
                      
                      for (String ID : clientIDs) {
                      	FlexClient flexClient = flexClientManager.getFlexClient(ID);
                      }
                      and from the flex client i got the flex sessions (HttpFlexSession) and the principal (UsernamePasswordAuthenticationToken) with following code

                      Code:
                      List<HttpFlexSession> clientSessions = flexClient.getFlexSessions();
                      UsernamePasswordAuthenticationToken principal = clientSessions.get(0).getUserPrincipal();
                      don't know if this is the best way to implement this. i'll be trying your solution this weekend.

                      thanks for you help

                      Comment

                      Working...
                      X