Spring Security OAuth2 Google授权重定向URI提示需完整认证如何解决
你遇到的问题由两个配置问题共同导致:
- Spring Security的权限校验规则中未将Google OAuth2的回调重定向URI加入白名单,所有未明确放行的路径都要求登录认证
- 自定义的JwtFilter全局拦截所有请求校验JWT,而Google回调的请求不会携带业务JWT,会被过滤器拦截抛出认证异常
步骤1:修改SecurityConfig放行OAuth2相关路径
在configure(HttpSecurity http)方法的authorizeRequests配置块中,新增OAuth2回调地址和授权入口的放行规则:
@Override public void configure(HttpSecurity http) throws Exception { http.cors() .and() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()) .and() .authorizeRequests() .antMatchers("/auth/sign-up").permitAll() .antMatchers("/auth/sign-in").permitAll() .antMatchers("/auth/refresh").permitAll() // 新增放行规则,若你的项目配置了server.servlet.context-path=/api则无需加/api前缀 .antMatchers("/api/login/oauth2/code/google").permitAll() .antMatchers("/oauth2/authorization/google").permitAll() .anyRequest() .authenticated() .and() .oauth2Login() .and() .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); }
步骤2:修改JwtFilter跳过回调地址的JWT校验
调整JwtFilter中的判断逻辑,将OAuth2回调地址加入JWT校验白名单:
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String requestUrl = ((HttpServletRequest) servletRequest).getRequestURL().toString(); String token = jwtProvider.resolveToken((HttpServletRequest) servletRequest); // 新增排除oauth2回调地址的判断 if (!requestUrl.endsWith("auth/refresh") && !requestUrl.contains("login/oauth2/code/google")) { try { if (token != null && jwtProvider.validateToken(token)) { Authentication authentication = jwtProvider.getAuthentication(token); if (authentication != null) { SecurityContextHolder.getContext().setAuthentication(authentication); } } } catch (JwtAuthenticationException e) { SecurityContextHolder.clearContext(); throw new JwtAuthenticationException("Access token is expired or invalid"); } } filterChain.doFilter(servletRequest, servletResponse); }
修改完成后重启项目即可正常访问Google OAuth2回调地址。
内容的提问来源于stack exchange,提问作者SislaOpir
相关产品推荐
相关产品推荐

