【发布时间】:2021-06-12 07:18:39
【问题描述】:
我有一个登录控制器,如果凭据错误 - 应该返回 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();
}
我得到的当前 Json 是 -
{
"timestamp": "2021-03-14T23:34:49.038+00:00",
"status": 403,
"error": "Forbidden",
"message": "",
"path": "/auth/login/"
}
目标是在 json 中获取消息,即凭据有问题。非常感谢您的帮助:)
【问题讨论】:
标签: java spring spring-boot