1

I'm trying to do a get request with headers because in my backEnd there is a check for the token which I generate in the login. But for some reason, I can't obtain the Authorization header and I print all the headers in the console and I don't see my header

here is the code of my service in Angular 6

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpErrorResponse } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { Usuario } from '../clases/usuario';
import { throwError } from 'rxjs';

constructor(private http: HttpClient) {}
getAllUsers(token: string) {
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'my-auth-token'
    })
  };
  httpOptions.headers = httpOptions.headers.set('Authorization', token);
  return this.http.request('GET', this.usuarioUrl, httpOptions)
    .pipe(
      map((resp: Usuario[]) => {
        this.usuarios = resp;
        return this.usuarios;
      }),
      catchError(this.handleError)
    );
}

here is my filter in my backEnd

public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
    if (!(((HttpServletRequest) request).getRequestURI().endsWith("/auth/login") ||
        ((HttpServletRequest) request).getRequestURI().endsWith("/auth/signup"))) {

      HttpServletRequest httpRequest = (HttpServletRequest) request;
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      String authHeader = httpRequest.getHeader(AuthUtils.AUTH_HEADER_KEY);
      Enumeration < String > test = httpRequest.getHeaderNames();
      while (test.hasMoreElements()) {
        String headerName = test.nextElement();
        logger.info("Header " + headerName);
        logger.info("getHeader " + httpRequest.getHeader(headerName));
      }
      logger.info("AuthHeader " + authHeader);
      if (StringUtils.isEmpty(authHeader) || authHeader.split(" ").length != 1) {
        logger.error("No token");
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTH_ERROR_MSG);
      } else {
        JWTClaimsSet claimSet = null;
        try {
          claimSet = (JWTClaimsSet) AuthUtils.decodeToken(authHeader);
        } catch (ParseException e) {
          httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_ERROR_MSG);
          return;
        } catch (JOSEException e) {
          httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_INVALID_MSG);
          return;
        }
        // ensure that the token is not expired
        if (new DateTime(claimSet.getExpirationTime()).isBefore(DateTime.now())) {
          httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, EXPIRE_ERROR_MSG);
        } else {
          chain.doFilter(request, response);
        }
      }
    } else {
      chain.doFilter(request, response);
    }

and my console is this

2018-09-16 19:57:00.877  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header host
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader localhost:8091
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header connection
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader keep-alive
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header access-control-request-method
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader POST
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header origin
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader http://localhost:4200
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header user-agent
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header access-control-request-headers
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader authorization,content-type
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header accept
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader */*
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header accept-encoding
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader gzip, deflate, br
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : Header accept-language
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : getHeader es-ES,es;q=0.9
2018-09-16 19:57:00.878  INFO 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : AuthHeader null
2018-09-16 19:57:00.878 ERROR 8880 --- [nio-8091-exec-7] py.edu.una.rest.filters.AuthFilter       : No token

how can obtain the Authorization header in my backend to check? please Help! why doesn't it reach my backEnd?

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Andrés Planás
  • 103
  • 1
  • 6

1 Answers1

0

Please use below code in filter to allow OPTIONS methods requests, the changes I made are mainly here:

if(httpRequest.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            chain.doFilter(request, response);
        } 

To understand why OPTIONS are required to please read answer from this thread: OPTIONS requests and CORS preflight OPTIONS request, this will solve your problem for now.

Your filter method code in AuthFilter

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if(httpRequest.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS.name())) {
            chain.doFilter(request, response);
        } else {
            if (!(((HttpServletRequest)request).getRequestURI().endsWith("/auth/login")
                    || ((HttpServletRequest)request).getRequestURI().endsWith("/auth/signup"))){

                String authHeader = httpRequest.getHeader(AuthUtils.AUTH_HEADER_KEY);
                Enumeration<String> prueba = httpRequest.getHeaderNames();
                while ( prueba.hasMoreElements()) {
                    String headerName = prueba.nextElement();
                    logger.info("Header "+ headerName);
                    logger.info("getHeader "+httpRequest.getHeader(headerName));
                }
                logger.info("AuthHeader "+ authHeader);
                if (StringUtils.isEmpty(authHeader) || authHeader.split(" ").length != 1) {
                    logger.error("No tiene token");
                    httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTH_ERROR_MSG);
                } else {
                    JWTClaimsSet claimSet = null;
                    try {
                        claimSet = (JWTClaimsSet) AuthUtils.decodeToken(authHeader);
                    } catch (ParseException e) {
                        httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_ERROR_MSG);
                        return;
                    } catch (JOSEException e) {
                        httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_INVALID_MSG);
                        return;
                    }
                    // ensure that the token is not expired
                    if (new DateTime(claimSet.getExpirationTime()).isBefore(DateTime.now())) {
                        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, EXPIRE_ERROR_MSG);
                    } else {
                        chain.doFilter(request, response);
                    }
                }
            }else{
                chain.doFilter(request, response);
            }
        }

    }

Recommended:

I will recommend to use Spring security to manage your Auth Filter and OPTIONS requests from overriding http like below:

@Override
protected void configure(HttpSecurity http) throws Exception
{
     http
    .csrf().disable()
    .authorizeRequests()
      .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()//allow CORS option calls
      .antMatchers("/resources/**").permitAll()
      .anyRequest().authenticated()
    .and()
    .//add filter here

}
kj007
  • 6,073
  • 4
  • 29
  • 47