1

When I send correct user/password request to my authenticate service, it return jwt, otherwise this errors enter image description here

and this he should show if request is wrong.

When i send jwt token everything is fine. But if Authorization is empty response body is empty too with status 200 (OK). If the token is incorrect then Postman also issues an empty response body with a status 401, as the followingenter image description here

I need Postman to display the error in the response body, as in the first screenshot, while he does it in Intellij idea.

Here's my codes

Custome exception

@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

  private static final long serialVersionUID = -7858869558953243875L;

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
                       AuthenticationException authException) throws IOException {

      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Jwt authentication failed");
  }
}

JwtUtill

@Service
public class JwtUtil implements Serializable {

    private static final long serialVersionUID = -2550185165626007488L;

    private String Secret_Key = "Secret key";

    public String extractUsername(String token) {
        return extractClaim(token, Claims::getSubject);
    }

    public Date extractExpiration(String token) {
        return extractClaim(token, Claims::getExpiration);
    }

    public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token);
        return claimsResolver.apply(claims);
    }

    private Claims extractAllClaims(String token) {
        return Jwts.parser().setSigningKey(Secret_Key).parseClaimsJws(token).getBody();
    }

    private Boolean isTokenExpired(String token) {
        return extractExpiration(token).before(new Date());
    }

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {

        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 10 * 60 * 1000))
                .signWith(SignatureAlgorithm.HS512, Secret_Key).compact();
    }

    public boolean validateToken(String token, UserDetails userDetails) {
            final String username = extractUsername(token);
            return (username.equals(userDetails.getUsername()) && isTokenExpired(token));
    }
}

JwtFilter

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserDetailsServiceImp userDetailsServiceImp;


    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return new AntPathMatcher().match("/authenticate", request.getServletPath());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , FilterChain filterChain) throws ServletException, IOException {

            final String requestHeader = httpServletRequest.getHeader("Authorization");

            String name = null;
            String jwt = null;

            if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
                jwt = requestHeader.substring(7);
                name = jwtUtil.extractUsername(jwt);
            }

            if (name != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = userDetailsServiceImp.loadUserByUsername(name);
                    if (jwtUtil.validateToken(jwt, userDetails)) {
                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        usernamePasswordAuthenticationToken
                                .setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    }
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
    }
}

SecurityConfig

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImp userDetailsService;

    @Autowired
    JwtFilter jwtFilter;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,"/authenticate").permitAll()
                .antMatchers(HttpMethod.GET,"/hello").permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

}

and RestController

@RestController
public class AuthenticationController {

    @Autowired
    public AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsServiceImp userDetailsService;

    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/hello")
    public String hello(){
        return "Hello new User";
    }

    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest jwtRequest) throws Exception{
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(jwtRequest.getName(), jwtRequest.getPassword()));
        }catch(BadCredentialsException e){
            throw new Exception("Incorrect username and password", e);
            }

        final UserDetails userDetails = userDetailsService.loadUserByUsername(jwtRequest.getName());

        final String token = jwtUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));

    }
}
  • Your response content length shows 315 bytes. So I think its not empty. Did you check the raw tab of postman rather than pretty ? – Kris Feb 28 '20 at 09:32
  • Please let us know you requested from Postman – Laminoo Lawrance Feb 28 '20 at 09:33
  • @Kris, its headers length.Raw,Preview and Visualize,also empty. – Haytham Kenway Feb 28 '20 at 11:39
  • @LaminooLawrance in first request i been asked for jwt(sent username and password)in second requeste i asked for "Hello new User" string in REstController,by setting SecurityContextHolder with jwt in Authorization request(second request) – Haytham Kenway Feb 28 '20 at 11:53
  • The solution to this problem has been discussed [here](https://stackoverflow.com/questions/19767267/handle-spring-security-authentication-exceptions-with-exceptionhandler) – Arashaad Ari Davidson Feb 02 '22 at 14:27
  • The solution to this problem has been discussed [here](https://stackoverflow.com/questions/19767267/handle-spring-security-authentication-exceptions-with-exceptionhandler) – Arashaad Ari Davidson Feb 02 '22 at 14:28

0 Answers0