作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在我的应用程序中使用 JWT 实现 Spring 安全性,每当进行未经授权的调用时,它都会返回以下响应
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
响应 json 如下所示
{
"timestamp": 1497832267379,
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/path"
}
除此之外,我还可以发送我自己的自定义响应,例如:
{
"code":401,
"message":"The request is unauthorized"
}
感谢任何帮助
编辑
我将代码更新为以下格式:
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
//response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
Status unauthorizedEntry = new Status();
unauthorizedEntry.setCode(401);
unauthorizedEntry.setMessage("Unauthorized Entry");
Map<String, Object> unauthorizedEntryResponse = new HashMap<>();
unauthorizedEntryResponse.put("status", unauthorizedEntry);
objectMapper.writeValue(response.getOutputStream(), unauthorizedEntry);
response.flushBuffer();
}
我的状态类如下:
public class Status {
int code;
String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
现在我收到 200 响应,但屏幕上没有显示任何内容。它是完全空白的。感谢您的帮助!
最佳答案
你可以尝试添加一个controller advice
@RestController
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(UsernameNotFoundException.class, DataAccessException.class)
@ResponseStatus(HttpStatus.SC_UNAUTHORIZED)
@ResponseBody ErrorInfo
UnauthorizeExceptionInfo(HttpServletRequest req, Exception ex) {
return new ErrorInfo(req.getRequestURL(), ex);
}
}
和ErrorInfo.class
@JsonIgnore
public final StringBuffer url;
public final String ex;
public ErrorInfo(StringBuffer stringBuffer, Exception ex) {
this.url = stringBuffer;
this.ex = ex.getLocalizedMessage();
}
当您抛出新的 UsernameNotFoundException 时, Controller 将处理响应。
而且我想如果密码/电子邮件不匹配,异常会从 CustomUserDetailsService 中的 @Override public loadUserByUsername 中抛出。
此处有更多详细信息:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
关于java - 我如何在 Spring 发送自己的回复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620783/
我是一名优秀的程序员,十分优秀!