spring 如何在Sping Boot 3.0+上解决CORS

xfyts7mz  于 2023-04-10  发布在  Spring
关注(0)|答案(1)|浏览(149)

Spring boot版本3.0.+Spring Security中,身份验证不起作用,并且所有POST请求都不起作用。
CORS策略已阻止从源“http://localhost:3000”访问位于“http://localhost:9090/api/rest/users/auth”的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
然而,GET请求工作,并没有给予这个错误。所有建议工作在3.0以下的Spring boot版本。类型https://reflectoring.io/spring-cors/不工作。我使用REST配置与JWT Token实现WebMvcConfigurer
我已经尝试在请求的前端和后端的响应端连接所有推荐的头,但没有任何帮助。显然,问题是在这些版本的非常小的。谁遇到过这个问题并解决了它,请回复。

@Override
protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE, PATCH");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "Accept-Encoding, origin, content-type, accept, token, x-auth-token, Access-Control-Allow-Origin, " +
                    "Access-Control-Allow-Methods, Access-Control-Max-Age, Access-Control-Allow-Headers, " +
                    "Content-Language, Content-Length, Keep-Alive, Authorization");


@RestController
@RequestMapping("/users")
@Slf4j
@SecurityRequirement(name = "Bearer Authentication")
@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*")
//localhost:9090/api/rest/users
public class UserController extends GenericController<User, UserDTO>
{
    private final CustomUserDetailsService customUserDetailsService;
    private final JWTTokenUtil jwtTokenUtil;
    private final UserService userService;

    public UserController(UserService userService,
                          CustomUserDetailsService customUserDetailsService,
                          JWTTokenUtil jwtTokenUtil) {
        super(userService);
        this.customUserDetailsService = customUserDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }
    @PostMapping("/auth")
    public ResponseEntity<?> auth(@RequestBody LoginDTO loginDTO) {
        Map<String, Object> response = new HashMap<>();
        log.info("LoginDTO: {}", loginDTO);
        UserDetails foundUser = customUserDetailsService.loadUserByUsername(loginDTO.getLogin());
        log.info("foundUser, {}", foundUser);
        if (!userService.checkPassword(loginDTO.getPassword(), foundUser)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Ошибка авторизации!\nНеверный пароль");
        }
        String token = jwtTokenUtil.generateToken(foundUser);
        response.put("token", token);
        response.put("username", foundUser.getUsername());
        response.put("authorities", foundUser.getAuthorities());
        return ResponseEntity.ok().body(response);
    }
}

@Configuration
    @EnableWebSecurity
    public class WebSecurityConfig {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
                // by default uses a Bean by the name of corsConfigurationSource
                .cors(withDefaults())
                ...
            return http.build();
        }
    
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
            configuration.setAllowedMethods(Arrays.asList("GET","POST"));
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }

    import {useAuthUserAppStore} from "@/store/app";
import LoginDTO from "@/models/LoginDTO";

class AuthService {
  login(loginDTOUser: LoginDTO) {
    const user = {
      login: loginDTOUser.login,
      password: loginDTOUser.password
    }
    const serializedUser = JSON.stringify(user);
    return http
      .post('/users/auth', serializedUser)
      .then(response => {
        if (response.data.accessToken) {
          useAuthUserAppStore().changeAuthUser(JSON.stringify(response.data))
          console.log(useAuthUserAppStore().authUser)
        }

        return response.data;
      });
  }
4zcjmb1e

4zcjmb1e1#

在类JWTSecurityConfig中,我删除了bean:

@Bean
public HttpFirewall httpFirewall() {       
    StrictHttpFirewall firewall = new 
    StrictHttpFirewall();       
    firewall.setAllowUrlEncodedPercent(true);
    firewall.setAllowUrlEncodedSlash(true);
    firewall.setAllowSemicolon(true);
    firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
    return firewall;
}

相关问题