It’s wrong to think that you get what you put in.

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a8f506f26~tplv-t2oaga2asx-image.image

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, specifiedjsonSerialization mode
@JsonSerialize(using = CustomOauthExceptionSerializer.class)
public class CustomOauthException extends OAuth2Exception {
    public CustomOauthException(String msg) {
        super(msg); }}Copy the code

New CustomOauthExceptionSerializer

  • addCustomOauthExceptionSerialization 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

  • addCustomWebResponseExceptionTranslatorTo 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 customcustomWebResponseExceptionTranslator
@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 customAuthExceptionEntryPointUsed fortokanVerification 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

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a95131f78~tplv-t2oaga2asx-image.image

Token abnormal

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a8944f75a~tplv-t2oaga2asx-image.image

Blocking access

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a88807c3b~tplv-t2oaga2asx-image.image

Token failure

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a8f7dd59d~tplv-t2oaga2asx-image.image

The code download

  • Github:github.com/longfeizhen…
  • Gitee:gitee.com/merryyou/se…

Recommend the article

  1. Java creates the blockchain family
  2. Spring Security source code analysis series
  3. Spring Data Jpa series
  4. All about Trees in Data Structures (Java Edition)
  5. SpringBoot+Docker+Git+Jenkins realize easy continuous integration and continuous deployment

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/5/27/163a194a87e01e0c~tplv-t2oaga2asx-image.image

🙂🙂🙂 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?