spring-security 为什么我的控制器不向Postman返回令牌

9udxz4iz  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(148)

我正在用Spring with Security和JWT开发一个API,这是登录的控制器方法,登录返回一个,但在Postman中,它不在主体中显示标记。
这是登录方法控制器:

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

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

这是JwtEntryPoint

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

验证响应

@Setter
@Getter

public class AuthenticationResponse {
    private String jwt;

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

验证控制器

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

身份验证请求

@Setter
@Getter

public class AuthenticationRequest {
    private String email;
    private String password;
}
r6hnlfcb

r6hnlfcb1#

您不会以任何方式返回令牌,只会返回文本"Hiii""AHHHHHH"

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

请尝试以下操作:

AuthenticationResponse response = new AuthenticationResponse(jwt);

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

相关问题