我有一个登录控制器,如果凭据是坏的,它应该返回badcredentialsexception,并以json格式显示消息,但是我得到的不是403响应。
我的代码:
控制器-
@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(@Valid @RequestBody AuthenticationRequest data) {
try {
System.out.println(data);
String email = data.getEmail();
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, data.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtTokenProvider.createToken(email);
AuthenticationResponse response = new AuthenticationResponse(email, token);
return ok(response);
} catch (AuthenticationException ex) {
throw new BadCredentialsException(messageSource.getMessage("authController.invalidCredentials", null, null));
}
}
证券配置-
http
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.and()
.apply(new JwtConfigurer(jwtTokenProvider))
.and()
.cors().and().csrf()
.disable();
令牌创建-
public String createToken(String username) {
Claims claims = Jwts.claims().setSubject(username);
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(HS256, secretKey)
.compact();
}
我现在得到的是-
{
"timestamp": "2021-03-14T23:34:49.038+00:00",
"status": 403,
"error": "Forbidden",
"message": "",
"path": "/auth/login/"
}
目标是在json中获得消息,即凭证有问题。非常感谢您的帮助:)
2条答案
按热度按时间jjjwad0x1#
因为默认的身份验证入口点是
org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
您可以这样覆盖默认身份验证入口点:您还可以检查异常类型:
r1wp621o2#
试试这个:
证券配置