Caros,
Minha aplicacao em Vue envia uma requisicao para a aplicacao em Spring Boot 3 (Spring Security + JWT).
O Token é gerado corretamente e enviado, porém no Filter ele nao consegue ler o hearder Authorization porque esta nulo.
Já coloquei .cors.disable, já coloquei o cors configuration, porem nao funciona.
Eu li no stackoverflow que poderia ser por que eu rodas as duas aplicacoes no endereco localhost, porem com portas diferentes. Porem, eu nao entendi qual solucao eu poderia dar.
@Component
public class AuthenticationFilter extends OncePerRequestFilter{
private TokenService tokenService;
private UserRepository userRepository;
public AuthenticationFilter(TokenService tokenService, UserRepository userRepository) {
this.tokenService = tokenService;
this.userRepository = userRepository;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String token = this.retrieveToken(request);
if (tokenService.isTokenValid(token)) {
String username = tokenService.getUsername(token);
Optional<User> user = userRepository.findByUsername(username);
System.out.println(user.get().getUsername());
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
user.get(), null, user.get().getAuthorities());
authentication.setDetails(
new WebAuthenticationDetailsSource().buildDetails(request)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
private String retrieveToken(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty() || token.startsWith("Bearer") ) {
return null;
}
return token.substring(7, token.length());
}
}
@Configuration @EnableWebSecurity public class SecurityConfigurations {
@Autowired
private TokenService tokenService;
@Autowired
private UserRepository userRepository;
@Bean
public UserDetailsService userDetailService() {
return new AuthService();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf().disable()
.authorizeHttpRequests()
.requestMatchers(HttpMethod.POST, "/auth").permitAll()
.and()
.authorizeHttpRequests()
.requestMatchers(HttpMethod.GET, "/api/**").authenticated()
.and()
.cors()
.and().addFilterBefore(new AuthenticationFilter(tokenService, userRepository), UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(authenticationProvider())
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.build();
}
@Bean
public AuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider authenticationProvider=new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.authenticationProvider(authenticationProvider())
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return getMd5(charSequence.toString());
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return getMd5(charSequence.toString()).equals(s);
}
};
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source =
new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
config.setAllowedOrigins(Arrays.asList("http://localhost:8080"));
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}