简体   繁体   中英

Spring request.getHeader not reading Authorization value from angular request

I'm currently working on a Spring+Angular project. When I'm trying to intercept a request and set its header with angular, Spring is not finding the Authorization header.

My JwtRequestFilter is looking like this:

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

  private MyUserDetailsService userDetailsService;
  private JwtUtil jwtUtil;

  @Autowired
  public JwtRequestFilter(MyUserDetailsService userDetailsService,
      JwtUtil jwtUtil) {
    this.userDetailsService = userDetailsService;
    this.jwtUtil = jwtUtil;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    final String authorizationHeader = request.getHeader("Authorization");
    /*Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      System.out.println("Header  " + headerNames.nextElement());
    }*/
    Enumeration<String> blabla = request.getHeaderNames();
    while (blabla.hasMoreElements()) {
      String header = blabla.nextElement();
      System.out.println("Header  " + header);
      System.out.println("Value  " + request.getHeader(header));
    }
    String username = null;
    String jwt = null;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
      jwt = authorizationHeader.substring(7);
      username = jwtUtil.extractUsername(jwt);
    }
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails ud = this.userDetailsService.loadUserByUsername(username);
      if (jwtUtil.validateToken(jwt, ud)) {
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(ud,
            null,ud.getAuthorities());
        upat.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(upat);
      }
    }
    response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Expose-Headers", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    filterChain.doFilter(request, response);
  }
}

While the Angular HTTPInterceptor class:

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req : HttpRequest<any>, next: HttpHandler) {
    let token = localStorage.getItem('jwt');
    const lo = /login/gi;
    const re = /register/gi;
  if (req.url.search(re) === -1 && req.url.search(lo) === -1) {
    let authService = this.injector.get(UserService);
    let update = {
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    };
    req = req.clone(update)
    console.log(req)
  }
    return next.handle(req);
  }
}

I tried debugging it as well, but request.getHeader is always getting null value, but if I try Postman, it's working fine. When I try printing out all the Headers with Spring, there is no header for Authorization, so I suspect it's an Angular side issue.

On Angular side: Console logs as the image shows the header should be getting the Authorization, Bearer. Network source

At the moment I'm at a loss what the problem could.

I'm currently working on a Spring+Angular project. When I'm trying to intercept a request and set its header with angular, Spring is not finding the Authorization header.

My JwtRequestFilter is looking like this:

@Component
public class JwtRequestFilter extends OncePerRequestFilter {

  private MyUserDetailsService userDetailsService;
  private JwtUtil jwtUtil;

  @Autowired
  public JwtRequestFilter(MyUserDetailsService userDetailsService,
      JwtUtil jwtUtil) {
    this.userDetailsService = userDetailsService;
    this.jwtUtil = jwtUtil;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    final String authorizationHeader = request.getHeader("Authorization");
    /*Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      System.out.println("Header  " + headerNames.nextElement());
    }*/
    Enumeration<String> blabla = request.getHeaderNames();
    while (blabla.hasMoreElements()) {
      String header = blabla.nextElement();
      System.out.println("Header  " + header);
      System.out.println("Value  " + request.getHeader(header));
    }
    String username = null;
    String jwt = null;
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
      jwt = authorizationHeader.substring(7);
      username = jwtUtil.extractUsername(jwt);
    }
    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      UserDetails ud = this.userDetailsService.loadUserByUsername(username);
      if (jwtUtil.validateToken(jwt, ud)) {
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(ud,
            null,ud.getAuthorities());
        upat.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(upat);
      }
    }
    response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
    response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
    response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Expose-Headers", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    filterChain.doFilter(request, response);
  }
}

While the Angular HTTPInterceptor class:

@Injectable()
export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req : HttpRequest<any>, next: HttpHandler) {
    let token = localStorage.getItem('jwt');
    const lo = /login/gi;
    const re = /register/gi;
  if (req.url.search(re) === -1 && req.url.search(lo) === -1) {
    let authService = this.injector.get(UserService);
    let update = {
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    };
    req = req.clone(update)
    console.log(req)
  }
    return next.handle(req);
  }
}

I tried debugging it as well, but request.getHeader is always getting null value, but if I try Postman, it's working fine. When I try printing out all the Headers with Spring, there is no header for Authorization, so I suspect it's an Angular side issue.

On Angular side: Console logs as the image shows the header should be getting the Authorization, Bearer. Network source

At the moment I'm at a loss what the problem could.

先生,您能解释更多吗?

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM