小编典典

如何在spring获得会话对象?

spring

我对Spring和Spring安全性比较陌生。

我试图编写一个程序,需要使用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是某个类的对象,我可以跨多个用户请求在整个服务器代码中对其进行访问。


阅读 458

收藏
2020-04-12

共1个答案

小编典典

// 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的管理器中添加过滤器。

编辑:作为附带问题,你实际上要做什么,我不确定你是否需要访问HttpSessionretieveUser方法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;
}
2020-04-12