Search code examples
javarequestjwthttp-headers

Not setting headers for request


I have an Angular 7 app and an API in Java Spring with JTW. The app must at each request in the API send the token, but this is not happening, and so all requests return the 401 error.

app modules

     ...

        @NgModule

({
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule, 
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        {
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        },
      ],
      bootstrap: [AppComponent]
    })

    export class AppModule {

    }

AuthInterceptor

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { GeneralService } from '../_service/general.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private generalService: GeneralService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            }
        });

       console.log(req);
       return next.handle(req);
    }
}

Request

listAll() {
     return this.http.get('http://localhost:8080/api/listAll');
}

async get() {
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  }

Result of console.log(req);

Looks like okay, the authorization and the token is there

enter image description here

The request

Dont pass the token here :c

enter image description here

Erros

OPTIONS 401 Access to XMLHttpRequest at'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I done the same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request.


Solution

  • Thanks for the comments, I was able to formulate a solution, I modified my WebSecurityConfig.java api file, the problem was not the angular requests. Thanks to all.

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private ParametersProperties parameters;
    
        @Resource(name = "userService")
        private UserDetailsService userDetailsService;
    
        @Autowired
        private JwtAuthenticationEntryPoint unauthorizedHandler;
    
        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Autowired
        public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                    .passwordEncoder(encoder());
        }
    
        @Bean
        public JwtAuthenticationFilter authenticationTokenFilterBean() {
            return new JwtAuthenticationFilter();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and().csrf().disable().
                    authorizeRequests()
                    .antMatchers(
                             "/swagger-resources/**",
                             "/swagger-ui.html",
                             "/webjars/**",
                             "/h2/**",
                             "/auth/signin",
                    ).permitAll()
                    /* the saver is the line below*/ 
                    .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    
            http
                    .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
                    .headers().frameOptions().sameOrigin();
        }
    
        @Bean
        public BCryptPasswordEncoder encoder(){
            return new BCryptPasswordEncoder();
        }
    }