CORS Policy with Spring boot and Angular

Discussão em 'Angular' iniciado por vinicius.vaga, Outubro 27, 2024.

  1. I'm developing an Angular application that must log in to a SpringBoot application. The Backend is structured to perform authentication using username and password and, when authenticated, return a JWT token to the frontend.

    This structure works when I use postman, as shown below. enter image description here enter image description here

    However, when I use my application to make these requests, a CORS Policy error is generated. enter image description here Here is my Angular Component: import { Component } from '@angular/core';

    import { FormsModule } from '@angular/forms';
    import { HttpClient } from '@angular/common/http';

    @Component({
    selector: 'app-loginscreen',
    templateUrl: './loginscreen.component.html',
    styleUrls: ['./loginscreen.component.css']
    })
    export class LoginscreenComponent {
    constructor(private httpClient: HttpClient) { }
    public inputUsername: string = "";
    public inputPassword: string = "";


    login() {
    // preparar requisição http
    // Suponhamos que você tenha uma URL e os dados de login
    const url = 'http://localhost:8080/auth/login';
    const dadosDeLogin = {
    username: this.inputUsername,
    password: this.inputPassword
    };
    const headers = { 'content-type': 'application/json'}


    this.httpClient.post(url, dadosDeLogin, { headers })
    .subscribe(data => {
    console.log(data);
    })

    }



    }


    Here is my SecurityFilter class:

    @Component
    public class SecurityFilter extends OncePerRequestFilter {
    @Autowired
    TokenService tokenService;
    @Autowired
    AdministratorRepository administratorRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    var token = this.recoverToken(request);
    if(token != null){
    var login = tokenService.validateToken(token);
    UserDetails user = administratorRepository.findByUsername(login);

    // Requests CORS
    response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");


    var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    filterChain.doFilter(request, response);
    }

    private String recoverToken(HttpServletRequest request) {
    var authHeader = request.getHeader("Authorization");
    if(authHeader == null) return null;
    return authHeader.replace("Bearer ", "");
    }
    }


    And here is my SecurityConfig class:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    @Autowired
    SecurityFilter securityFilter;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    return httpSecurity
    .csrf(csrf -> csrf.disable())
    .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    .authorizeHttpRequests(authorize -> authorize
    .requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/auth/login")).permitAll()
    .requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/auth/register")).permitAll()
    .requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/users")).hasRole("ADMIN")
    .anyRequest().authenticated()
    )
    .addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
    .build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
    }
    }


    I've tried a few ways to remove this error by setting CORS policy in my backend, but nothing seems to work. Can you help me?

    I tried enabling cross origin through my backend

    Continue reading...

Compartilhe esta Página