Estou desenvolvendo um projeto com base nos conhecimentos aprendidos neste curso e nesse projeto configurei uma classe de configurações de segurança, conforme ensinado no curso, e também criei uma classe de configuração de Cors conforme abaixo:
package com.minascafe.api.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.exposedHeaders("Access-Control-Allow-Origin");
}};}}
Uma de minhas classes controller é:
package com.minascafe.api.controllers;
import com.minascafe.api.entities.User;
import com.minascafe.api.infra.security.TokenService;
import com.minascafe.api.record.AuthenticationDTO;
import com.minascafe.api.record.LoginResponseDTO;
import com.minascafe.api.record.RegisterDTO;
import com.minascafe.api.repositories.UserRepository;
import com.minascafe.api.services.AuthorizationService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("auth")
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository repository;
@Autowired
private TokenService tokenService;
@Autowired
private AuthorizationService authorizationService;
@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid AuthenticationDTO data){
try {
var usernamePassword = new UsernamePasswordAuthenticationToken(data.login(), data.senha());
var auth = this.authenticationManager.authenticate(usernamePassword);
var token = tokenService.generateToken((User) auth.getPrincipal());
return ResponseEntity.ok(new LoginResponseDTO(token));
} catch (AuthenticationException e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Erro no login :(");
}}
@PostMapping("/register")
@CrossOrigin
public ResponseEntity register(@RequestBody @Valid RegisterDTO data) {
if (this.repository.findByLogin(data.login()) != null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Usuário já cadastrado!");
String encryptedPassword = new BCryptPasswordEncoder().encode(data.password());
User newUser = new User(data.login(), encryptedPassword, data.role());
this.repository.save(newUser);
return ResponseEntity.status(HttpStatus.OK).body("Usuário cadastrado com sucesso!");
}}.
Quando executo e utilizo o frontend chamando o endpoint 'localhost/auth/login', com método POST passando um valor de usuario e de senha retorna na tela: 'Usuário ou senha incorretos, tente novamente!' e no console do navegador retorna um erro de cabeçalho ausente:
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request .
To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.
Note that if an opaque response is sufficient, the request's mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque).
1 request
Request Status Preflight Request (if problematic) Header Problem Invalid Value (if available)
login blocked
login Access-Control-Allow-Origin Missing Header.
Mas esse cabeçalho 'Access-Control-Allow-Origin' já foi configurado em meu arquivo de Cors. Simplesmente não estou entendendo. Alguém pode me dar uma luz, por favor?