内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我试图编写一个程序,在这里我需要使用Spring安全性在服务器端对用户进行身份验证,
我想出了以下几点:
public class CustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider{ @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException { System.out.println("Method invoked : additionalAuthenticationChecks isAuthenticated ? :"+usernamePasswordAuthenticationToken.isAuthenticated()); } @Override protected UserDetails retrieveUser(String username,UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { System.out.println("Method invoked : retrieveUser"); //so far so good, i can authenticate user here, and throw exception if not authenticated!! //THIS IS WHERE I WANT TO ACCESS SESSION OBJECT } }
我的用法是,当用户经过身份验证时,我需要放置一个属性,如下所示:
session.setAttribute("userObject", myUserObject);
myUserObject是某个类的对象,我可以通过多个用户请求访问整个服务器代码。
用这个 org.springframework.web.context.request.RequestContextHolder
// example usage
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
这将由标准的spring mvc dispatch servlet填充,但是如果你使用的是不同的Web框架,可以添加org.springframework.web.filter.RequestContextFilter
一个过滤器web.xml
来管理持有者。
编辑:只是作为一个侧面问题你究竟在做什么,我不知道你应该需要访问HttpSession
的retieveUser
方法UserDetailsService
。Spring安全会将UserDetails对象放在会话中为你做任何事情。它可以通过访问SecurityContextHolder
:
public static UserDetails currentUserDetails(){
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
if (authentication != null) {
Object principal = authentication.getPrincipal();
return principal instanceof UserDetails ? (UserDetails) principal : null;
}
return null;
}
建议访问会话的最佳做法是:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}