All Downloads are FREE. Search and download functionalities are using the official Maven repository.

matrix.business.oauth2.config.AuthorizationResponseBodyAdvice Maven / Gradle / Ivy

package matrix.business.oauth2.config;

import matrix.boot.common.dto.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.endpoint.AbstractEndpoint;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenKeyEndpoint;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 验证返回拦截器
 *
 * @author wangcheng
 * 2021/12/30
 **/
@SuppressWarnings("NullableProblems")
@RestControllerAdvice
public class AuthorizationResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        return AbstractEndpoint.class.isAssignableFrom(returnType.getContainingClass())
                || CheckTokenEndpoint.class.isAssignableFrom(returnType.getContainingClass())
                || TokenKeyEndpoint.class.isAssignableFrom(returnType.getContainingClass());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof OAuth2Exception) {
            response.setStatusCode(HttpStatus.OK);
            OAuth2Exception oAuth2Exception = (OAuth2Exception) body;
            return Result.fail(oAuth2Exception.getMessage(), oAuth2Exception.getHttpErrorCode());
        }
        return Result.success(body);
    }
}