我正在我的应用程序中使用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条响应,但屏幕上没有任何显示。它是完全空白。任何帮助表示赞赏!
@JsonIgnore
public final StringBuffer url;
public final String ex;
public ErrorInfo(StringBuffer stringBuffer, Exception ex) {
this.url = stringBuffer;
this.ex = ex.getLocalizedMessage();
}
并且当您将抛出新的UsernameNotFoundException时,控制器将处理响应。
而且我想如果密码/电子邮件不匹配,则将异常从CustomUserDetailsService放入您的@Override公共loadUserByUsername中。
此处有更多详细信息:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
这应该为您工作: