java - 得到错误的异常响应 (403)
问题描述
我有一个登录控制器,如果凭据错误 - 应该返回 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 中获取消息,即凭证有问题。非常感谢您的帮助:)
解决方案
因为默认的身份验证入口点是org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
您可以像这样覆盖默认身份验证入口点:
public static class Message {
private String message;
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
private static final ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void configure(HttpSecurity http) throws Exception {
// set your authentication entry point
http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // you could replace your custom HTTP status
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(objectMapper.writeValueAsString(new Message(authException.getMessage())));
out.flush();
});
http
.httpBasic().disable()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.and()
.apply(new JwtConfigurer(jwtTokenProvider))
.and()
.cors().and().csrf()
.disable();
}
您还可以检查异常类型:
if (authException instanceof BadCredentialsException) {
// Do somthing
}
推荐阅读
- apache-calcite - Apache Calcite - 似乎无法解析 DDL 语句
- python - 在python中导入files.py的问题
- python - 使用 python-requests 发送带有字典数组的 JSON
- python - python中复杂多重继承中的构造函数调用序列
- c# - 在测试运行期间单击按钮会打开一个空白窗口 selenium c#
- java - 如何使用 Java 中的 Restful API 删除 json 文件中的元素?
- javascript - Vue.js,将值从组件发送到 router/index.js
- sparql - 组合 SPARQL 查询
- c# - 在 asp.net web 表单和 Ajax 中发送字符串类型数据的问题
- typo3 - 哪个版本的扩展构建器适用于 TYPO3 9.5 LTS?