【问题标题】:Spring security with Ajax – logged user details使用 Ajax 的 Spring 安全性——记录的用户详细信息
【发布时间】:2013-03-15 02:57:39
【问题描述】:

我已经使用 AuthenticationEntryPoint 和 SimpleUrlAuthenticationSuccessHandler 通过 Ajax 实现了用户身份验证。

现在我需要将登录的用户名输入到我的脚本变量中。

谁能帮我解决这个问题?

MyAuthenticationSuccessHandler

public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private Log log = LogFactory.getLog(MyAuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {

        log.info("point-2-->"+authentication.getName()); //this prints what I need.

        // This is actually not an error, but an OK message. It is sent to avoid redirects.
        response.sendError(HttpServletResponse.SC_OK);

    }
}

我的 JavaScript 函数

$("#login").on('click', function(e) {
        e.preventDefault();
        $.ajax({url: getHost() + "/j_spring_security_check",
            type: "POST",
            beforeSend: function(xhr) {
                xhr.withCredentials = true;
            },
            data: $("#loginForm").serialize(),
            success: function(response, options) {
                    // We get a success from the server
                    //I need to get user name here
            },
            error: function(result, options) {
                    // We get a failure from the server...
                $(".error").remove();
                $('#j_username').before('<div class="error">Login failed, please try again.</div>');
        }


        });
    });

我已经为不同的问题附上了所有相关文件。请访问下面的链接进行检查。

Spring Security; custom-filter and user-service-ref not working together

【问题讨论】:

    标签: ajax spring-security user-data logged


    【解决方案1】:

    我找到了解决办法。

    我只是进行了另一个 Ajax 调用,并在那里捕获了已登录的用户。

    我的 JavaScript 函数

    success: function(response, options) {
                        // We get a success from the server
                        //I need to get user name here
    
        $.post('/api/loggeduser', function(data) {
               $('#loggeduser').html(data);
            }); 
    },
    

    登录用户控制器

    @RequestMapping(value = "/api/loggeduser", method = RequestMethod.POST)
           public String printWelcome(ModelMap model, Principal principal ) {
    
            try {
    
                String name = null;
    
                if (principal!=null) {
    
               name = principal.getName();
    
              }
    
                    model.addAttribute("username", name);
    
    
    
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 2017-10-02
      • 2019-03-08
      • 1970-01-01
      • 2020-07-24
      • 2012-04-03
      • 2020-08-28
      • 1970-01-01
      • 2011-07-03
      相关资源
      最近更新 更多