When I send correct user/password request to my authenticate service, it return jwt, otherwise this errors
введите описание изображения здесь
и это он должен показать, если запрос неправильный.
Когда я отправляю JWT токен все Это хорошо. Но если Авторизация пуста, тело ответа тоже пусто со статусом 200 (ОК). Если токен неверен, то почтальон также выдает пустое тело ответа со статусом 401, так как следующий введите здесь описание изображения
Мне нужно, чтобы почтальон отобразил ошибку в теле ответа, так как на первом скриншоте, пока он делает это в идее Intellij.
Вот мои коды
Обычное исключение
@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();
}
}
и 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));
}
}