从spring Boot 上构建的react应用程序调用API时出错

t0ybt7op  于 2023-08-02  发布在  Spring
关注(0)|答案(1)|浏览(113)

我正在构建一个网站,我正在调用我的API,这些API是在Sping Boot 上构建的,但得到了Cors错误。当从 Postman 调用API时,API工作正常。
浏览器控制台出错-CORS策略已阻止从源“http://localhost:3000”访问“http://localhost:9090/addUser”上的XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。
这是我的用户控制器,我正在从react调用addUser

package com.brs.controllers;
import java.util.List;
import javax.validation.Valid;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import com.brs.entity.Users;
import com.brs.service.interfaces.IUserService;

@RestController
public class UsersController {
    @Autowired
    private IUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @CrossOrigin(origins = "*")
    @PostMapping("/addUser") @SneakyThrows
    public Users addUsers(@Valid @RequestBody Users users)
    {
        users.setPassword(passwordEncoder.encode(users.getPassword()));

        return userService.addUser(users);
    }

    @GetMapping("/viewUser") @SneakyThrows
    public Users viewUsers(@RequestParam String userName)
    {
        return userService.viewUser(userName);
    }
    
    @GetMapping("/viewAllUsers")
    public List<Users> viewAllUsers()
    {
        return userService.viewAllUsers();
    }

    @DeleteMapping("/deleteUser") @SneakyThrows
    public Users deleteUser(@RequestParam String userName)
    {
        return userService.deleteUser(userName);
    }
    
    @PutMapping("/updateUser") @SneakyThrows
    public Users updateUser(@Valid @RequestBody Users user) {
        return userService.updateUser(user);
    }

    @GetMapping("/getUserByUserName") @SneakyThrows
    public Users getUserByUserName(@RequestParam String userName){return userService.getUserByUserName(userName);}

    @PutMapping("/updateUserData") @SneakyThrows
    public Users updateUserData(@Valid @RequestBody Users user) {
        return userService.updateUserData(user);
    }
}

字符串
这是我的安全配置文件

package com.brs.securityconfiguration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers( "/token", "/addUser")
                .permitAll()
                .antMatchers(HttpMethod.GET, "/bus")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.DELETE, "/bus", "/deleteReservation", "/deleteUser")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/bus", "/addReservation")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.PUT, "/bus", "/updateReservation", "/updateUser")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/buses", "/viewAllReservation", "/viewReservation")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/buses", "/viewFeedback", "/viewAllFeedBack", "/viewReservation", "/viewUser", "/viewAllUsers", "/searchBus")
                .hasRole("USER")
                .antMatchers(HttpMethod.GET, "/viewBusByType")
                .hasRole("ADMIN")
                .antMatchers(HttpMethod.GET, "/viewBusByType")
                .hasRole("USER")
                .antMatchers(HttpMethod.POST, "/addFeedback", "/addReservation")
                .hasRole("USER")
                .antMatchers(HttpMethod.PUT, "/updateFeedback", "/updateReservation")
                .hasRole("USER")
                .antMatchers(HttpMethod.DELETE, "/deleteReservation")
                .hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(jwtAuthenticationFilter , UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}


我该怎么做才能从任何域调用我的api?
我试过为整个控制器类定义crosorOrigin,我也试过全局cors配置,但似乎什么都不起作用!

kpbwa7wx

kpbwa7wx1#

尝试通过添加.cors()在Spring Security级别启用CORS支持,如下所示:

@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

字符串
然后,您需要在SpringMVC中启用CORS支持。对于Sping Boot 应用程序,您可以按以下方式执行:

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}


参见https://spring.io/guides/gs/rest-service-cors/

相关问题