用户注册成功后,我尝试将用户重定向到登录后页面并尝试从 SecurityContextHolder.getContext().getAuthentication(); 获取 Activity 用户;返回 null。
这是我在用户成功注册时设置上下文的方式
UsernamePasswordAuthenticationToken authenticatedUser = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
authenticatedUser.setDetails(userDetails);
if(authenticatedUser.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}
然后我使用response.sendRedirect(url)将用户重定向到x页面;
在 Controller 方法中,我尝试将当前用户设置为
@RequestMapping("/<pattern>")
public @ResponseBody <method_name>(HttpServletRequest req,HttpServletResponse resp){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(auth==null){
System.out.println("this is null");
}
else{
// do something
}
}
我在控制台中看到的文本为“this is null”。
如何在整个用户期间从 SecurityContext() 保留当前用户/主体,直到用户注销。
最佳答案
我找到了解决方案。
问题出在该特定 URI 组的标记的模式属性上。
之前是/path/* 并且失败了。我将其更改为/path/** 并且成功了。
如果有人能解释这两种模式匹配(/* 和/**)之间的关系,将会很有帮助。
关于java - Spring Security : SecurityContextHolder. getContext().getAuthentication() 在用户注册用户并重定向到登录后页面后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30871615/