From cacf02681bfdda7926379d37d58ad1a21e398e1a Mon Sep 17 00:00:00 2001 From: lrj <owen.stl@gmail.com> Date: 星期六, 04 十月 2025 19:08:12 +0800 Subject: [PATCH] fix(auth): 对无 Authorization 的 GraphQL 请求默认匿名放行到解析层,避免 400/403;公开查询仍优先识别后放行 --- backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java | 37 +++++++++++++++++-------------------- 1 files changed, 17 insertions(+), 20 deletions(-) diff --git a/backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java b/backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java index 273489e..e7a03b1 100644 --- a/backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java +++ b/backend/src/main/java/com/rongyichuang/auth/filter/JwtAuthenticationFilter.java @@ -134,18 +134,12 @@ ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request; byte[] content = wrapper.getContentAsByteArray(); if (content.length > 0) { - return new String(content, wrapper.getCharacterEncoding()); + String encoding = wrapper.getCharacterEncoding() != null ? wrapper.getCharacterEncoding() : "UTF-8"; + return new String(content, encoding); } } - - // 濡傛灉涓嶆槸鍖呰鍣紝灏濊瘯鐩存帴璇诲彇锛堝彲鑳戒細娑堣�楄姹備綋锛� - StringBuilder buffer = new StringBuilder(); - String line; - java.io.BufferedReader reader = request.getReader(); - while ((line = reader.readLine()) != null) { - buffer.append(line); - } - return buffer.toString(); + // 涓嶄粠鍘熷璇锋眰娴佽鍙栵紝閬垮厤涓嬫父缁勪欢鎷夸笉鍒拌姹備綋瀵艰嚧 400 + return null; } catch (Exception e) { logger.warn("璇诲彇璇锋眰浣撳け璐�", e); return null; @@ -215,27 +209,30 @@ // 鍏堟鏌uthorization澶达紝濡傛灉娌℃湁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璇锋眰缂哄皯鏈夋晥鐨凙uthorization澶翠笖涓嶆槸鍏紑鏌ヨ"); - sendUnauthorizedResponse(response); + // 鏃犳硶鍙潬璇诲彇/鍒ゅ畾璇锋眰浣撴椂锛岄粯璁や互鍖垮悕韬唤鏀捐鍒癎raphQL灞傦紝鐢卞悇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; } -- Gitblit v1.8.0