spring-security 使用 AJAX 的Spring安全性-记录的用户详细信息

dzhpxtsq  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(177)

我已经通过 AJAX 使用AuthenticationEntryPoint和SimpleUrlAuthenticationSuccessHandler实现了用户身份验证。
现在,我需要将登录用户名输入到脚本变量中。
有人能帮我吗?

我的验证成功处理程序

  1. public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
  2. private Log log = LogFactory.getLog(MyAuthenticationSuccessHandler.class);
  3. @Override
  4. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
  5. Authentication authentication) throws IOException, ServletException {
  6. log.info("point-2-->"+authentication.getName()); //this prints what I need.
  7. // This is actually not an error, but an OK message. It is sent to avoid redirects.
  8. response.sendError(HttpServletResponse.SC_OK);
  9. }
  10. }

我的JavaScript函数

  1. $("#login").on('click', function(e) {
  2. e.preventDefault();
  3. $.ajax({url: getHost() + "/j_spring_security_check",
  4. type: "POST",
  5. beforeSend: function(xhr) {
  6. xhr.withCredentials = true;
  7. },
  8. data: $("#loginForm").serialize(),
  9. success: function(response, options) {
  10. // We get a success from the server
  11. //I need to get user name here
  12. },
  13. error: function(result, options) {
  14. // We get a failure from the server...
  15. $(".error").remove();
  16. $('#j_username').before('<div class="error">Login failed, please try again.</div>');
  17. }
  18. });
  19. });

我已经为不同的问题附上了所有相关的文件。请访问下面的链接检查他们。
Spring Security; custom-filter and user-service-ref not working together

ifsvaxew

ifsvaxew1#

我找到了解决办法。
我只是进行了另一个 AJAX 调用,并捕获了登录用户。

我的JavaScript函数

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

登录用户控制器

  1. @RequestMapping(value = "/api/loggeduser", method = RequestMethod.POST)
  2. public String printWelcome(ModelMap model, Principal principal ) {
  3. try {
  4. String name = null;
  5. if (principal!=null) {
  6. name = principal.getName();
  7. }
  8. model.addAttribute("username", name);
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }
  12. }
展开查看全部

相关问题