Why doesn't my controller return a token to Postman

Viewed 34

I'm developing an API with Spring with Security and JWT, and this is the controller method to login, and the login return a but in Postman it doesn't show the token in the body.

This is the login method controller:

@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    BookingUserService bookingUserService;
    @Autowired
    RoleService roleService;

    @Autowired
    JWTUtil jwtUtil;


    @PostMapping(path = "/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody BookingUser registerBookingUser) {
        if (bookingUserService.existsByEmail(registerBookingUser.getEmail())) {
            return ResponseEntity.ok("Email already exists");
        }
       BookingUser bookingUser = new BookingUser(registerBookingUser.getName(), registerBookingUser.getLastName(), registerBookingUser.getEmail(), passwordEncoder.encode(registerBookingUser.getPassword()), registerBookingUser.getCity(), registerBookingUser.getRole());
       Role role = new Role();
       role = roleService.findByName(String.valueOf(RoleName.client)).get();
       if(registerBookingUser.getRole().equals("admin"))
           role = roleService.findByName(String.valueOf(RoleName.admin)).get();
       bookingUser.setRole(role);
       bookingUserService.createUser(bookingUser);
       return ResponseEntity.status(HttpStatus.CREATED).body("User successfully created");
    }

    @Deprecated
    @PostMapping(path = "/login")
    public ResponseEntity<?> loginUser(@RequestBody AuthenticationRequest request) {
        try {
            Authentication authentication = authenticationManager.authenticate
                    (new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtil.generateToken(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            //user = (Optional<BookingUser>) authentication.getPrincipal();
            AuthenticationResponse response = new AuthenticationResponse(jwt);
            System.out.println("JWT AHHHHH: ");

            if(!jwt.isEmpty()){
                return new ResponseEntity<>("Hiii", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
            }

        } catch (BadCredentialsException e) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
    }
}

This the JwtUtil

@Component
public class JWTUtil {
    private static final String KEY = "mG9\\n2,^obBu[8n.~MpVzbB5tHnuYF<KRE/LnQrQ<q@]wQP46vo^x{3vEN?3uN/E";
    @Deprecated
    public String generateToken(Authentication authentication) {
        BookingUser user = (BookingUser) authentication.getPrincipal();
        Map<String, Object> claims = new HashMap<>();
        claims.put("lastname", user.getLastName());
        claims.put("name", user.getName());

        return Jwts.builder()
                .setSubject(user.getUsername())
                .addClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
                .signWith(SignatureAlgorithm.HS256, KEY).compact();
    }
    public Boolean validateToken(String token, UserDetails userDetails) {
        return userDetails.getUsername().equals(extractUsername(token)) && !isTokenExpired(token);
    }
    public String extractUsername(String token) {
        return getClaims(token).getSubject();
    }
    public Boolean isTokenExpired(String token) {
        return getClaims(token).getExpiration().before(new Date());
    }
    @Deprecated
    private Claims getClaims(String token) {
        return Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
    }
}

This the JwtEntryPoint

@Component
public class JwtEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
    }
}

AuthenticationResponse

@Setter
@Getter

public class AuthenticationResponse {
    private String jwt;

    public AuthenticationResponse(String jwt) {
        this.jwt = jwt;
    }
}

AuthController

@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    BookingUserService bookingUserService;
    @Autowired
    RoleService roleService;

    @Autowired
    JWTUtil jwtUtil;


    @PostMapping(path = "/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody BookingUser registerBookingUser) {
        if (bookingUserService.existsByEmail(registerBookingUser.getEmail())) {
            return ResponseEntity.ok("Email already exists");
        }
       BookingUser bookingUser = new BookingUser(registerBookingUser.getName(), registerBookingUser.getLastName(), registerBookingUser.getEmail(), passwordEncoder.encode(registerBookingUser.getPassword()), registerBookingUser.getCity(), registerBookingUser.getRole());
       Role role = new Role();
       role = roleService.findByName(String.valueOf(RoleName.client)).get();
       if(registerBookingUser.getRole().equals("admin"))
           role = roleService.findByName(String.valueOf(RoleName.admin)).get();
       bookingUser.setRole(role);
       bookingUserService.createUser(bookingUser);
       return ResponseEntity.status(HttpStatus.CREATED).body("User successfully created");
    }

    @Deprecated
    @PostMapping(path = "/login")
    public ResponseEntity<?> loginUser(@RequestBody AuthenticationRequest request) {
        try {
            Authentication authentication = authenticationManager.authenticate
                    (new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtil.generateToken(authentication);
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            //user = (Optional<BookingUser>) authentication.getPrincipal();
            AuthenticationResponse response = new AuthenticationResponse(jwt);
            System.out.println("JWT AHHHHH: ");

            if(!jwt.isEmpty()){
                return new ResponseEntity<>("Hiii", HttpStatus.OK);
            } else {
                return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
            }

        } catch (BadCredentialsException e) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
    }
}

AuthenticationRequest

@Setter
@Getter

public class AuthenticationRequest {
    private String email;
    private String password;
}
1 Answers

You are not returning the token in any way, only the text "Hiii" or "AHHHHHH".

if(!jwt.isEmpty()){
    return new ResponseEntity<>("Hiii", HttpStatus.OK);
} else {
    return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
}

Try something like the following:

AuthenticationResponse response = new AuthenticationResponse(jwt);

if(!jwt.isEmpty()){
    return new ResponseEntity<>(response, HttpStatus.OK);
} else {
    return new ResponseEntity<>("AHHHHHH", HttpStatus.OK);
}
Related