首页 > 解决方案 > 仅使用过滤器即可使用带有 Cookie 的 Spring Security

问题描述

我有一个从 Web 客户端调用的后端应用程序。通过调用,将发送一个 cookie,其中包含一个已由客户端成功验证的会话 ID。

在后端,我只想检查 cookie 发送的 session id 是否有效。(CSRF 也会被考虑)

简单地创建一个过滤器来联系 sso 系统以检查 cookie 中包含的会话 ID 是否还不够?

安全配置:

    http.authorizeRequests()
            .antMatchers("/api/**").permitAll()
            .and()
            .addFilter(new SsoFilter(authenticationManager()));

和一个过滤器:

public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws
          IOException, ServletException {
    Cookie[] cookies = request.getCookies();

    if(cookies == null || cookies.length == 0){
      filterChain.doFilter(request, response);
      return;
    }

    Cookie tokenCookie = null;

    for (Cookie cookie : cookies){
      if (cookie.getName().equals(COOKIE_NAME)){
        tokenCookie = cookie;
      }
    }

    UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(tokenCookie.getValue());
    SecurityContextHolder.getContext().setAuthentication(authenticationToken);

    filterChain.doFilter(request, response);
  }

  private UsernamePasswordAuthenticationToken getAuthentication(String token) {
    final Useruser= ssoService.validateToken(token);
    return new UsernamePasswordAuthenticationToken(user,null, null);
  }

标签: spring-security

解决方案


推荐阅读