0

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.

Sabrina B.
  • 306
  • 1
  • 8
  • 23
  • Can you explain? – Sabrina B. May 27 '19 at 19:09
  • Probably the server isn't set up correctly so is denying the options request, but we can't tell from what you've posted. See e.g. https://stackoverflow.com/a/40723041/3001761 – jonrsharpe May 27 '19 at 19:19
  • The angular not sended the token in the request is not a problem? – Sabrina B. May 27 '19 at 20:02
  • I done the same request with insonmia (passed Authorization and the token) e all is okay, the problem is with the angular request. – Sabrina B. May 27 '19 at 20:05
  • Did you read the link? A preflight options request shouldn't include credentials. Unless you did the whole CORS cycle and made an options request from insomnia, you're wrong about where the problem is. – jonrsharpe May 27 '19 at 20:06
  • Is the interceptor correctly extending the Http class in your `app.module`? – Ritchie May 27 '19 at 20:19
  • @Ritchie this isn't getting as far as the point where that would matter. The credentials *don't get added to the preflight request*. – jonrsharpe May 27 '19 at 20:21
  • @Ritchie I think so, I put my app modules in the question, can you look there? – Sabrina B. May 27 '19 at 21:17

2 Answers2

0

First of all, if you haven't done so already you need to provide the interceptor in the root module. Add this to the providers-field:

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

Second, this could be related to this issue. Make sure you only have one import of HttpClientModule in the entire app.

Also check out this discussion from an issue on the Angular repo. The same behavior can occur if you import some module from a third party package that imports HttpClientModule.

andbjer
  • 554
  • 2
  • 9
0

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();
    }
}
Sabrina B.
  • 306
  • 1
  • 8
  • 23