简体   繁体   中英

set session attribute after login

I need to set ID of a user as a session attribute after login using Java EE form login module.

Right now, after login, I send another HTTP request, which sets the ID as a session attribute, but I need to do it in one step. What is the best way to do it?

login module configuration in standalone.xml:

<login-module code="com.MyLoginModule" flag="required">
    <module-option name="dsJndiName" value="java:/PostgresDS"/>
    <module-option name="principalsQuery" value="select password from appuser where email=?"/>
    <module-option name="rolesQuery" value="select 'AUTHENTICATED', 'Roles' from appuser where email=?"/>
    <module-option name="hashAlgorithm" value="custom"/>
</login-module>

Additional request after login (RESTEasy):

@GET
@Path("/web")
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@Context HttpServletRequest hsr) throws MyRuntimeException{
    User u;
    HttpSession session = hsr.getSession();
    u = um.getUserByMail(hsr.getUserPrincipal().getName());
    session.setAttribute("userId", u.getId());
    return u;
}

MyLoginModule:

public class MyLoginModule extends DatabaseServerLoginModule {
@Override
public String createPasswordHash(String username, String password, String digestOption){code}
}

I assume you're using JBoss here....

You could for example enhance the

org.apache.catalina.authenticator.FormAuthenticator

(used as standard authenticator in JBoss ) and implement your additional logic there.

public class MyFormAuthenticator extends FormAuthenticator{

@Override
public boolean  authenticate(Request request,HttpServletResponse response,LoginConfig config){
   boolean success = super.authenticate(request,response,config);
   if(success){
      Session session = request.getSessionInternal(false); // Use the existing session
      session.put .... // the action which you want to do
   }
   return success;
}

Don't forget to adjust the jboss-web.xml (placed in WEB-INF folder):

<jboss-web>
   <context-root>myContext</context-root>
   <valve>
     <class-name>MyFormAuthenticator</class-name>
   </valve>
</jboss-web>

Maven

Ensure that you use this Maven Dependency (not jboss-as-web):

<dependency>
  <groupId>org.jboss.web</groupId>
  <artifactId>jbossweb</artifactId>
  <version>7.5.10.Final</version>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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