It’s wrong to think that you get what you put in.
preface
When Spring Security Oauth2 login and authentication fails, the following exception information is returned by default
{
"error": "unauthorized"."error_description": "Full authentication is required to access this resource"
}
Copy the code
. It is inconsistent with our custom return information and has less description information. How to customize Spring Security Oauth2 exception information? The format is as follows:
{
"error": "400"."message": "Bad papers."."path": "/oauth/token"."timestamp": "1527432468717"
}
Copy the code
User-defined login failure exception information
New CustomOauthException
- Adds a custom exception class, specified
json
Serialization mode
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {
public CustomOauthException(String msg) {
super(msg); }}Copy the code
New CustomOauthExceptionSerializer
- add
CustomOauthException
Serialization implementation of
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
public CustomOauthExceptionSerializer(a) {
super(CustomOauthException.class);
}
@Override
public 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", "wrong username or password ");
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.writeEndObject(); }}Copy the code
Add CustomWebResponseExceptionTranslator
- add
CustomWebResponseExceptionTranslator
To be specified when a login exception occursexceptionTranslator
public class CustomOauthExceptionSerializer extends StdSerializer<CustomOauthException> {
public CustomOauthExceptionSerializer(a) {
super(CustomOauthException.class);
}
@Override
public 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", "wrong username or password ");
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.writeEndObject(); }}Copy the code
Modify MerryyouAuthorizationServerConfig
- Specifying custom
customWebResponseExceptionTranslator
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
// Extend token returns the result
if(jwtAccessTokenConverter ! =null&& jwtTokenEnhancer ! =null) {
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> enhancerList = new ArrayList();
enhancerList.add(jwtTokenEnhancer);
enhancerList.add(jwtAccessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(enhancerList);
//jwt
endpoints.tokenEnhancer(tokenEnhancerChain)
.accessTokenConverter(jwtAccessTokenConverter);
}
endpoints.exceptionTranslator(customWebResponseExceptionTranslator);
}
Copy the code
User-defined Token exception information
Add AuthExceptionEntryPoint
- The custom
AuthExceptionEntryPoint
Used fortokan
Verification failure message is returned
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws ServletException {
Map map = new HashMap();
map.put("error"."401");
map.put("message", authException.getMessage());
map.put("path", request.getServletPath());
map.put("timestamp", String.valueOf(new Date().getTime()));
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), map);
} catch (Exception e) {
throw newServletException(); }}}Copy the code
Add CustomAccessDeniedHandler
- The message is returned when authorization fails (forbidden)
@Slf4j
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Autowired
private ObjectMapper objectMapper;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setContentType("application/json; charset=UTF-8");
Map map = new HashMap();
map.put("error"."400");
map.put("message", accessDeniedException.getMessage());
map.put("path", request.getServletPath());
map.put("timestamp", String.valueOf(new Date().getTime()));
response.setContentType("application/json"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write(objectMapper.writeValueAsString(map)); }}Copy the code
Modify MerryyouResourceServerConfig
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.authenticationEntryPoint(new AuthExceptionEntryPoint())
.accessDeniedHandler(CustomAccessDeniedHandler);
}
Copy the code
Results the following
Abnormal login
Token abnormal
Blocking access
Token failure
The code download
- Github:github.com/longfeizhen…
- Gitee:gitee.com/merryyou/se…
Recommend the article
- Java creates the blockchain family
- Spring Security source code analysis series
- Spring Data Jpa series
- All about Trees in Data Structures (Java Edition)
- SpringBoot+Docker+Git+Jenkins realize easy continuous integration and continuous deployment
🙂🙂🙂 focus on wechat small program Java architect journey Bored on the commute? Still reading novels, news? Don’t know how to improve your skills? Here’s the Java architecture article you need. 1.5W + Java engineers are reading it. What are you waiting for?