【问题标题】:Spring Security: put additional attributes(properties) in the session on success AuthenticationSpring Security:在成功身份验证的会话中添加其他属性(属性)
【发布时间】:2012-03-11 03:51:53
【问题描述】:

只是一个简单的问题:在成功认证时向 HttpSession 添加属性(属性)的最佳方法是什么?以用户 ID 为例。

现在我在 UsernamePasswordAuthenticationFilter 中使用我自己的 SimpleUrlAuthenticationSuccessHandler 实现,并这样做:

public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication auth)
            throws IOException, ServletException {
        PersonBean person = (PersonBean) auth.getPrincipal();
        request.getSession().setAttribute("currentUserId", person .getId().toString());
        super.onAuthenticationSuccess(request, response, auth);

但我认为这不是一个好方法,因为还有其他方法可以进行身份​​验证(例如 RememberMe)。

那么我需要在这里使用什么?

【问题讨论】:

    标签: spring session authentication spring-security


    【解决方案1】:

    Spring 为您完成了所有这些工作,您必须创建一个表 *persistent_logins*,这是来自应用上下文的 sn-p 可能会有所帮助。官方文档describe in detail 需要什么:

    <security:http auto-config='true'>
      <security:intercept-url pattern="/**" access="ROLE_USER" />
      <security:form-login login-page="/Login"
         authentication-success-handler-ref="authenticationSuccessHandler"
         authentication-failure-url="/Login?login_error=1" />
      <security:remember-me data-source-ref="dataSource"
        user-service-ref="myUserService" />
    </security:http>
    

    然后您就可以从您应用中的任何位置访问主体对象,例如,下面显示了在 jsp 中输出用户名的标签:

    <sec:authentication property="principal.username" />
    

    从您的 java 代码中可以做到这一点:

    MyUser user = (MyUser) authentication.getPrincipal();
    

    【讨论】:

    • persistent_logins 表实际上与在会话中存储属性没有任何关系。这只是一个特殊的记住我的实现。不过,在身份验证对象中存储额外的自定义用户属性确实很有意义。
    【解决方案2】:

    答案是在春季论坛上给出的。 Link.

    一般来说,需要实现一个ApplicationListener来监听成功事件并在会话中放置额外的属性。

    但在我的情况下,它不需要在会话中存储属性。我可以像这里一样检索用户 ID:

    var userId = ${pageContext.request.userPrincipal.principal.id}
    

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多