Codex Assistant
14 小时以前 0a48616045ddce1562584543a0e89e5144051fde
backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java
@@ -169,7 +169,7 @@
     * 返回权限错误响应
     */
    private void sendUnauthorizedResponse(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"errors\":[{\"message\":\"没有权限访问,请先登录\",\"extensions\":{\"code\":\"UNAUTHORIZED\"}}]}");
    }
@@ -209,27 +209,30 @@
            // 先检查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",
                        "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;
            }