【发布时间】:2021-11-18 08:06:30
【问题描述】:
我必须从受资源服务器保护的浏览器中使用访问令牌调用 API,并使用 spring boot 2.4.6
GET API - http://127.0.0.1:9090/api/user/benz@gmail.com
当我调用上述 API 时,浏览器会抛出以下 CORS 阻塞异常
No 'access-control-allow-origin' header is present on the requested resource
WebSecurityConfig
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private AuthEntryPoint authEntryPoint;
public WebSecurityConfig(AuthEntryPoint authEntryPoint){
this.authEntryPoint=authEntryPoint;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().exceptionHandling().authenticationEntryPoint(authEntryPoint)
.and().authorizeRequests().antMatchers("/api/contact").permitAll()
.and().authorizeRequests().antMatchers("/api/forget/**").permitAll()
.and().authorizeRequests().antMatchers("/api/user/register","/api/user/login").permitAll()
.and().authorizeRequests().anyRequest().authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/contact")
.antMatchers("/api/forget/**")
.antMatchers("/api/user/register","/api/user/login");
}
}
交叉配置
@Configuration
public class CrossConfig {
@Bean
public WebMvcConfigurer crossConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
.allowedHeaders("*");
}
};
}
}
资源服务器配置
@Configuration
@EnableResourceServer
@EnableConfigurationProperties(SecurityProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
/............./
}
控制器
@CrossOrigin(origins = "*",maxAge = 3600)
@RestController
@RequestMapping("/api/user")
public class VoyageUserController {
private VoyageUserService voyageUserService;
public VoyageUserController(VoyageUserService voyageUserService){
this.voyageUserService=voyageUserService;
}
@GetMapping(value = "/{id}",produces = {MediaType.APPLICATION_JSON_VALUE})
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_MODERATOR','ROLE_ADMIN')")
public ResponseEntity<VoyageUserResponse> getUser(@PathVariable("id") String email){
return (email.trim().isEmpty()) ?
new ResponseEntity<>(HttpStatus.BAD_REQUEST) :
new ResponseEntity<>(voyageUserService.findVoyageUser(email),HttpStatus.OK);
}
}
使用 Axios 来自 React 的 API 请求
if(email){
axios.get(`http://127.0.0.1:9090/api/user/${email}`,{
headers:{
'Authorization':'bearer '+token}
})
.then(res=>{
const userDetail = res.data;
console.log(userDetail);
this.setState({
voyageUser:userDetail
});
this.setIsLogged(true);
}).catch(error=>{
console.log(error);
this.setIsLogged(false);
});
}
我已经完成了 StackOverflow 作为答案中可用的所有事情,但是浏览器仍然会引发 CORS 阻塞异常。
注意 - 我的代码中没有语法错误,如果问题包含某些内容,请忽略。
【问题讨论】:
标签: java reactjs spring spring-boot spring-security