Bom, em meu projeto estou realizando uma função de criação, usando POST, e estou usando a autenticação com tokens JWT. Até o momento consegui fazer o navegador guardar o token, porém ao enviá-lo no header, como será possível ver nos códigos abaixo, para fazer a autenticação, o Spring não reconhece esse parâmetro, retornando null. Vale dizer que estou recolhendo o token em um Filter.
Código JS:
// USER REGISTER FUNCTION //
const formConsumerRegister = document.querySelector("#consumer-register-form");
const message = document.querySelector("#alert");
formConsumerRegister.addEventListener("submit", (event) => {
event.preventDefault()
var formData = new FormData(formConsumerRegister);
var data = Object.fromEntries(formData);
var jsonData = JSON.stringify(data);
fetch("http://localhost:8080/consumer", {
mode: "cors",
method: "POST",
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`,
'Access-Control-Allow-Origin': 'http://localhost:8080',
'Access-Control-Allow-Credentials': 'true',
'Content-Type': 'application/json'
},
body: jsonData
})
.then(response => {
if(!response.ok){
message.innerHTML = "Error...";
message.style.color = "#FF0000";
throw new Error("HTTP Status " + response.status);
}
return response
})
.then(data => {
message.innerHTML = "Consumer created!";
message.style.color = "#00FF00";
window.location = "dashboardPage.html";
})
.catch(err => {
console.log(err)
message.innerHTML = "Auth Error...";
message.style.color = "#FF0000";
})
})
Filter no Spring:
@Component
public class SecurityFilter extends OncePerRequestFilter {
@Autowired
private TokenService tokenService;
@Autowired
private UserRepository userRepository;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
var tokenJWT = getToken(request);
if(tokenJWT != null){
var subject = tokenService.getSubject(tokenJWT);
System.out.println(subject);
var user = userRepository.findByUser(subject);
var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String getToken(HttpServletRequest request) {
var authHeader = request.getHeader("Authorization");
System.out.println(authHeader); // printando null aqui
if(authHeader != null){
return authHeader.replace("Bearer ", "");
}
return null;
}
}
Arquivo de configurações do Spring:
@Configuration
@EnableWebSecurity
public class SecurityConfigurations {
@Autowired
private SecurityFilter securityFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
return http.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(req -> {
req.requestMatchers("/login").permitAll();
req.requestMatchers("/login/verify").permitAll();
req.anyRequest().authenticated();
})
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public AuthenticationManager authManager(AuthenticationConfiguration config) throws Exception{
return config.getAuthenticationManager();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Abaixo tambem vou deixar o resultado recebido no console do navegador: