Angular 6,HtttpClient,带有后端Spring Boot!我的标题没有到达后端

时间:2018-09-17 00:26:04

标签: java angular spring-boot http-headers

我正在尝试向get发出headers请求,因为在我的后端中,我检查了登录名中生成的令牌。但是由于某种原因,我无法获得Authorization标头,并且在控制台中打印了所有标头,但看不到我的标头

这是我在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)
    );
}

这是我的后端过滤器

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);
    }

我的控制台是这个

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

如何在后端获取Authorization标头进行检查?请帮忙!为什么不到达我的后端?

1 个答案:

答案 0 :(得分:0)

请在过滤器中使用以下代码,以允许OPTIONS方法请求,我所做的更改主要是在这里:

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

要了解为什么需要OPTIONS才能阅读此线程OPTIONS requestsCORS preflight OPTIONS request的答案,这将立即解决您的问题。

您在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);
            }
        }

    }

推荐:

我建议使用Spring安全性通过覆盖如下的http来管理您的Auth Filter和OPTIONS请求:

@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

}