When I send correct user/password request to my authenticate service, it return jwt, otherwise this errors
enter image description here
如果请求有误,他应该显示出来。
当我发送jwt令牌时,一切都很好。但是,如果授权为空,则响应主体也为空,状态为200(确定)。如果令牌不正确,则邮递员还会发出状态为401的空响应正文,如下所示enter image description here
我需要Postman在响应主体中显示错误,如第一个屏幕截图所示,而他是在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));
}
}