我相对较新Spring和春季安全。
我试图编写一个程序,需要使用 Spring security 在服务器端对用户进行身份验证,
我想出了以下几点:
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 调度 servlet 填充,但如果您使用不同的 Web 框架,则需要添加org.springframework.web.filter.RequestContextFilter
作为你的过滤器web.xml
来管理持有者。
EDIT:作为一个附带问题,您实际上想做什么,我不确定您是否应该需要访问HttpSession
in the retieveUser
的方法UserDetailsService
。 Spring security 会以任何方式将 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)