| | |
| | | // 先检查Authorization头,如果没有token,再检查是否为公开查询 |
| | | String authHeader = request.getHeader("Authorization"); |
| | | if (authHeader == null || !authHeader.startsWith("Bearer ")) { |
| | | logger.debug("GraphQL请求没有Authorization头,检查是否为公开查询"); |
| | | logger.debug("GraphQL请求没有Authorization头,尝试判定是否为公开查询"); |
| | | |
| | | // 检查是否为公开查询 |
| | | // 尝试判定公开查询;如果能确定是公开查询则放行 |
| | | if (isPublicGraphQLQuery(wrappedRequest)) { |
| | | logger.debug("检测到公开GraphQL查询,允许匿名访问"); |
| | | |
| | | // 设置匿名认证,让Spring Security知道这是一个已认证的匿名用户 |
| | | AnonymousAuthenticationToken anonymousAuth = new AnonymousAuthenticationToken( |
| | | "anonymous", |
| | | "anonymous", |
| | | Arrays.asList(new SimpleGrantedAuthority("ROLE_ANONYMOUS")) |
| | | ); |
| | | SecurityContextHolder.getContext().setAuthentication(anonymousAuth); |
| | | logger.debug("为公开GraphQL查询设置匿名认证"); |
| | | |
| | | filterChain.doFilter(wrappedRequest, response); |
| | | return; |
| | | } |
| | | |
| | | logger.warn("GraphQL请求缺少有效的Authorization头且不是公开查询"); |
| | | sendUnauthorizedResponse(response); |
| | | // 无法可靠读取/判定请求体时,默认以匿名身份放行到GraphQL层,由各Resolver自行进行权限校验 |
| | | logger.debug("无法可靠判定是否为公开查询,设置匿名认证并交由GraphQL层处理"); |
| | | AnonymousAuthenticationToken anonymousAuth = new AnonymousAuthenticationToken( |
| | | "anonymous", |
| | | "anonymous", |
| | | Arrays.asList(new SimpleGrantedAuthority("ROLE_ANONYMOUS")) |
| | | ); |
| | | SecurityContextHolder.getContext().setAuthentication(anonymousAuth); |
| | | filterChain.doFilter(wrappedRequest, response); |
| | | return; |
| | | } |
| | | |