ajax - Getting logged in users with sessionRegistry not work when manually authenticate -


i use spring security3 , spring mvc3 build web project. there page called index.jsp, login user name , online user count displayed on top of screen. there 2 ways login system:

  1. from login page, use default configuration post 'j_spring_security_check'
  2. ajax login manually authentication

when use login page login index page, both of count of online information , user name show correctly. when use ajax login (manually authenticate), problem occurs: count of online user don't updated, displaying 0 while user name can show properly. part of controller:

@autowired @qualifier("authenticationmanager") authenticationmanager authenticationmanager; @autowired securitycontextrepository repository;  @requestmapping(value="/ajaxlogin") @responsebody public string performlogin(         @requestparam("j_username") string username,         @requestparam("j_password") string password,         httpservletrequest request, httpservletresponse response) {             usernamepasswordauthenticationtoken token =  new usernamepasswordauthenticationtoken(username, password);             try {                 authentication auth = authenticationmanager.authenticate(token);                 securitycontextholder.getcontext().setauthentication(auth);                 repository.savecontext(securitycontextholder.getcontext(), request, response);                 logger.info("authentication successfully! ");                 return "{\"status\": true}";             } catch (badcredentialsexception ex) {                 return "{\"status\": false, \"error\": \"bad credentials\"}";             } } 

spring-security.xml

<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-3.0.3.xsd">  <http auto-config="true" use-expressions="true">         <intercept-url pattern="/login" access="permitall" />     <intercept-url pattern="/index" access="permitall" />     <form-login login-page="/login" default-target-url="/index"         authentication-failure-url="/loginfailed" />     <logout logout-success-url="/logout" />      <session-management invalid-session-url="/index">         <concurrency-control max-sessions="1"             error-if-maximum-exceeded="false" />     </session-management> </http>  <authentication-manager alias="authenticationmanager">     <authentication-provider>         <jdbc-user-service data-source-ref="datasource"              users-by-username-query="                 select login_id,login_pwd, is_enabled                  t_user login_id=?"              authorities-by-username-query="                 select u.login_id, r.authority t_user u, t_roles r                  u.u_id = r.u_id , u.login_id =?  " />     </authentication-provider> </authentication-manager> 

method used online login user count:

public class basecontroller {     protected logger logger = logger.getlogger(this.getclass());      @autowired       sessionregistry sessionregistry;        @modelattribute("numusers")       public int getnumberofusers() {           logger.info("in getnumberofusers() ...");         return sessionregistry.getallprincipals().size();       }   } 

code used show login user name:

<div>         <security:authorize ifallgranted="role_user">             <p><a href="#todo">welcome <security:authentication property="principal.username" />!</a> &nbsp;&nbsp;&nbsp;             <a href="<c:url value="/j_spring_security_logout" />">logout</a></p>         </security:authorize>     </div> 

code used show count of logged in users:

<div style="color:#3cc457">         ${numusers} user(s) logged in!      </div> 

i guess because when manually authenticate, spring security not create new session user. validate write customized sessioncounterlistener.

public class sessioncounterlistener implements httpsessionlistener {  private logger logger = logger.getlogger(this.getclass());  private static int totalactivesessions;   public static int gettotalactivesession(){        return totalactivesessions;  }  @override public void sessioncreated(httpsessionevent event) {        totalactivesessions++;        logger.info("sessioncreated - add 1 session counter" + event.getsession().getid());    }  @override public void sessiondestroyed(httpsessionevent event) {        totalactivesessions--;        logger.info("sessiondestroyed - deduct 1 session counter" + event.getsession().getid());   }    

}

below key content of log file action sequence: normal login -> normal logout -> ajax login -> ajax logout.

sessiondestroyed - deduct 1 session 1spueddcmdao019udc43k3uumw sessioncreated - add 1 session 14nro6bzyjy0x1jtvnqjx31v1 sessiondestroyed - deduct 1 session 14nro6bzyjy0x1jtvnqjx31v1 sessioncreated - add 1 session e6jqz5qy6412118iph66xvaa1 

actually, ajax login/logout not give output.

so now, how can correct login user count? , why different authenticate ways has different method deal session? appreciated.

as manually adding principal securitycontext, not add user sessionregistry. need add user session sessionregistry manually.

securitycontextholder.getcontext().setauthentication(auth); sessionregistry.registernewsession(request.getsession().getid(), auth.getprincipal()); 

hope helps!!


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -