身份验证不起作用,并且所有POST
请求在Spring boot
版本3.0.+
的Spring Security
中都不起作用。它给出错误
访问'XMLHttpRequesthttp://localhost:9090/api/rest/users/auth'来自原点'http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在"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;
});
}
在类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;
}