Authorization Header returns null Springboot

Viewed 47

I am basically trying to implement JWT Authentication and am getting null value for request.getHeader("Authorization"); when using postman for my login API. This is my AuthTokenFilter class

    private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        String requestToken = request.getHeader("Authorization");
        String username = null;
        String jwt = parseJwt(request);
        if (jwt != null ) {
            try{
                username = jwtUtils.getUsernameFromToken(jwt);
            }catch(IllegalArgumentException  | MalformedJwtException e){
                throw new BadCredentialsException("INVALID_CREDENTIALS", e);
            }catch (ExpiredJwtException e){
                throw new ExpiredJwtException(e.getHeader(), e.getClaims(),"Expired Token", e);
            }

        }else{
            System.out.println("JWT token is null");
        }

        //After getting user
        if(username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
            UserDetails userDetails = this.employeeService.loadUserByUsername(username);
            try {
                if(this.jwtUtils.validateToken(jwt,userDetails)){
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    userDetails,
                                    null,
                                    userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            } catch (Exception e) {
                throw new RuntimeException("Invalid JWT Token",e);
            }
        }else{
            System.out.println("User is null or context is not empty");
        }


    filterChain.doFilter(request, response);
}

private String parseJwt(HttpServletRequest request) {
    String headerAuth = request.getHeader("Authorization");

    if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
        return headerAuth.substring(7, headerAuth.length());
    }

    return null;
}

}

I have added cors().and() in my config file also @CrossOrigin(origins = "*") above my controller.

Following is my SecurityConfig class

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
    http
            .cors().and().csrf().disable()
            .authorizeRequests()
            .antMatchers("api/v1/auth/login")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();
    http.authenticationProvider(authenticationProvider());
    http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
     return http.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

    authProvider.setUserDetailsService(employeeService);
    authProvider.setPasswordEncoder(passwordEncoder());

    return authProvider;
}

}

0 Answers
Related