SpringSecurity更改默认验证的异常提示

// 继承 AuthorizationServerConfigurerAdapter
// 重写下面的configure方法
	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		//配置端点
		endpoints.tokenStore(tokenStore)
			.authenticationManager(authenticationManager)
			.userDetailsService(userDetailsService)
			.tokenGranter(tokenGranter)
			.exceptionTranslator(new oAuth2ResponseExceptionTranslator());
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 异常转换器
 * @author l
 */
@Component
public class OAuth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    /**
     * 异常类型定义
     */
    public static final String ERROR = "error";
    public static final String DESCRIPTION = "error_description";
    public static final String URI = "error_uri";
    public static final String INVALID_REQUEST = "invalid_request";
    public static final String INVALID_CLIENT = "invalid_client";
    public static final String INVALID_GRANT = "invalid_grant";
    public static final String UNAUTHORIZED_CLIENT = "unauthorized_client";
    public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";
    public static final String INVALID_SCOPE = "invalid_scope";
    public static final String INSUFFICIENT_SCOPE = "insufficient_scope";
    public static final String INVALID_TOKEN = "invalid_token";
    public static final String REDIRECT_URI_MISMATCH = "redirect_uri_mismatch";
    public static final String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
    public static final String ACCESS_DENIED = "access_denied";
    /**
     * 其他异常
     */
    public static final String METHOD_NOT_ALLOWED = "method_not_allowed";
    public static final String SERVER_ERROR = "server_error";
    public static final String UNAUTHORIZED = "unauthorized";

    private static final ConcurrentHashMap<String, String> OAUTH2_ERROR_MAP = new ConcurrentHashMap<>();

    /*
     * 映射了部分
     */
    static {
        OAUTH2_ERROR_MAP.put(INVALID_CLIENT, "无效的客户端");
        OAUTH2_ERROR_MAP.put(INVALID_GRANT, "登录密码错误");
        OAUTH2_ERROR_MAP.put(INVALID_SCOPE, "权限不足");
        OAUTH2_ERROR_MAP.put(UNSUPPORTED_GRANT_TYPE, "不支持的授权模式类型");
        OAUTH2_ERROR_MAP.put(ACCESS_DENIED, "验证码不正确");
        OAUTH2_ERROR_MAP.put(METHOD_NOT_ALLOWED, "方法不允许访问");
        OAUTH2_ERROR_MAP.put(SERVER_ERROR, "服务器内部异常");
        OAUTH2_ERROR_MAP.put(UNAUTHORIZED, "未授权");
    }

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        // 尝试从异常堆栈中提取 SpringSecurityException。
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
        // 异常栈获取 OAuth2Exception 异常
        OAuth2Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
        if (ase != null) {
            return handleOAuth2Exception(ase);
        }
        System.out.println(e+"==========================");
        // 返回封装后的错误响应
        return new ResponseEntity<>(new OAuth2Exception(e.getMessage(),e),HttpStatus.BAD_REQUEST);
    }

    private ResponseEntity<OAuth2Exception> handleOAuth2Exception(OAuth2Exception e) {
        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        // 如果是未授权或权限不足,添加 WWW-Authenticate 头部
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }
        String oAuth2ErrorMessage = OAUTH2_ERROR_MAP.getOrDefault(e.getOAuth2ErrorCode(),"未知异常:" + e.getOAuth2ErrorCode());
        // 构造响应体
        OAuth2Exception responseBody = new OAuth2Exception(oAuth2ErrorMessage,e);
        // 返回 ResponseEntity
        return new ResponseEntity<>(responseBody, headers, HttpStatus.valueOf(status));
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值