简体   繁体   English

登录后设置会话属性

[英]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. 我需要在使用Java EE表单登录模块登录后将用户的ID设置为会话属性。

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. 现在,登录后,我发送另一个HTTP请求,它将ID设置为会话属性,但我需要一步完成。 What is the best way to do it? 最好的方法是什么?

login module configuration in standalone.xml: 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): 登录后的其他请求(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: MyLoginModule:

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

I assume you're using JBoss here.... 我假设你在这里使用JBoss ....

You could for example enhance the 你可以举例来说

org.apache.catalina.authenticator.FormAuthenticator org.apache.catalina.authenticator.FormAuthenticator

(used as standard authenticator in JBoss ) and implement your additional logic there. (在JBoss中用作标准验证器)并在那里实现您的附加逻辑。

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.xml(放在WEB-INF文件夹中):

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

Maven Maven的

Ensure that you use this Maven Dependency (not jboss-as-web): 确保您使用此Maven依赖项(而不是jboss-as-web):

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

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

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