SpringSecurity5-教程4-Cookie单点登录

/**
 * 从cookie获取 token,解析并设置登录态
 * 当cookie有token时,处理/oauth/authorize将不会再跳入登录页
 */
@Slf4j
@Getter
@Setter
@WebFilter("/*")
public class CookieSsoFilter extends OncePerRequestFilter {
    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getCookies() == null) {
            filterChain.doFilter(request, response);
            return;
        }
        String userToken = getUserToken(request);
        if (Strings.isBlank(userToken)) {
            filterChain.doFilter(request, response);
            return;
        }
        boolean tokenNotChanged = userToken.equals(session.getAttribute("usertoken"));
        if (tokenNotChanged) {
            filterChain.doFilter(request, response);
            return;
        }

        // 更新用户
        User user = userService.find(userToken);
        if (user == null) {
            filterChain.doFilter(request, response);
            return;
        }
        session.setAttribute("usertoken", usertoken);
        // 保存认证结果
        saveAuthentication(request, response, user);
        filterChain.doFilter(request, response);
    }

    private void saveAuthentication(HttpServletRequest request, HttpServletResponse response, user user) {
        List authorities = Lists.newArrayList();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER")); // /oauth/authorize等接口需要这个权限
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), authorities);
        authentication.setDetails(new WebAuthenticationDetails(request));
        HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
        SecurityContext securityContext = securityContextRepository.loadContext(holder);
        securityContext.setAuthentication(authentication);
        SecurityContextHolder.setContext(securityContext);
        securityContextRepository.saveContext(securityContext, holder.getRequest(), holder.getResponse());
    }
}

public String getUserToken(HttpServletRequest request) {
        return  Arrays.stream(request.getCookies())
                .filter(c -> c.getName().equals("userToken"))
                .findAny().map(Cookie::getValue).orElse(null);
}

你可能感兴趣的:(spring-security,spring)