付出就要得到回报,这种想法是错的。
[
https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a8f506f26~tplv-t2oaga2asx-image.image
](https://link.juejin.cn/?target=https%3A%2F%2Fp1-jj.byteimg.com%2Ftos-cn-i-t2oaga2asx%2Fgold-user-assets%2F2018%2F5%2F27%2F163a194a8f506f26~tplv-t2oaga2asx-image.image “https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a8f506f26~tplv-t2oaga2asx-image.image”)
前言
在使用Spring Security Oauth2
登录和鉴权失败时,默认返回的异常信息如下
{"error": "unauthorized","error_description": "Full authentication is required to access this resource"
}
。它与我们自定义返回信息不一致,并且描述信息较少。那么如何自定义Spring Security Oauth2
异常信息呢,下面我们简单实现以下。格式如下:
{
"error": "400",
"message": "坏的凭证",
"path": "/oauth/token",
"timestamp": "1527432468717"
}
自定义登录失败异常信息
新增CustomOauthException
- 添加自定义异常类,指定
json
序列化方式
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {public CustomOauthException(String msg) {super(msg);}
}
新增CustomOauthExceptionSerializer
- 添加
CustomOauthException
的序列化实现
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {public CustomOauthExceptionSerializer() {super(CustomOauthException.class);}@Overridepublic void serialize(CustomOauthException value, JsonGenerator gen, SerializerProvider provider) throws IOException {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();gen.writeStartObject();gen.writeStringField("error", String.valueOf(value.getHttpErrorCode()));gen.writeStringField("message", value.getMessage());
//gen.writeStringField("message", "用户名或密码错误");gen.writeStringField("path", request.getServletPath());gen.writeStringField("timestamp", String.valueOf(new Date().getTime()));if (value.getAdditionalInformation()!=null) {for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {String key = entry.getKey();String add = entry.getValue();gen.writeStringField(key, add);}}gen.writeEndO