我已经通过Ajax使用AuthenticationEntryPoint和SimpleUrlAuthentication成功处理程序实现了用户身份验证。
现在我需要将登录的用户名输入到我的脚本变量中。
有人能帮我吗?
我的身份验证成功处理程序
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性;自定义过滤器和用户服务参考不能一起工作
我找到了解决办法。
简单地,我打了另一个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();
}
}