Spring security oauth2 ExceptionTranslationFilter所抛异常处理

Spring security核心就是一组过滤器链。项目启动自动配置上的。

最核心的就是 Basic Authentication Filter 用来认证用户的身份;

一个过滤器处理一种认证方式;

对于username password认证过滤器来说,

  • 会检查是否是一个登录请求,
  • 是否包含username 和 password (也就是该过滤器需要的一些认证信息)
  • 如果不满足则放行给下一个

下一个按照自身职责判定是否是自身需要的信息,

basic的特征就是在请求头中有 Authorization:Basic eHh4Onh4 的信息

中间可能还有更多的认证过滤器。最后一环是 FilterSecurityInterceptor

这里会判定该请求是否能进行访问rest服务;判断的依据是:BrowserSecurityConfig中的配置;

如果被拒绝了就会抛出不同的异常(根据具体的原因)。

Exception Translation Filter 会捕获抛出的错误,然后根据不同的认证方式进行信息的返回提示

注意的是:绿色的过滤器可以配置是否生效,其他的都不能控制;

以上就是security最基本的一个原理,其他的衍生的功能都是基于这个架子进行扩展的

如何处理ExceptionTranslationFilter中所抛出的异常?

package com.healthy.security.server.handler;

import com.healthy.security.core.support.SimpleResponse;
import com.healthy.security.server.handler.exception.HealthyOauthException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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 org.springframework.web.HttpRequestMethodNotSupportedException;

import java.io.IOException;
import java.nio.file.AccessDeniedException;

/**
 * healthy translator that converts exceptions into {@link OAuth2Exception}s. The output matches the OAuth 2.0
 * specification in terms of error response format and HTTP status code.
 */
@Slf4j
@Component("healthyResponseExceptionTranslator")
public class HealthyResponseExceptionTranslator implements WebResponseExceptionTranslator<SimpleResponse> {

    private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    @Override
    public ResponseEntity<SimpleResponse> translate(Exception e) throws Exception {

        // Try to extract a SpringSecurityException from the stacktrace
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);

        // 异常栈获取 OAuth2Exception 异常
        Exception exception = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);


        // 异常栈中有OAuth2Exception
        if (exception != null) {
            return handleOAuth2Exception((OAuth2Exception) exception);
        }

        exception = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
                causeChain);

        if (exception != null) {
            return handleOAuth2Exception(new HealthyOauthException(e.getMessage(), e));
        }

        exception = (AccessDeniedException) throwableAnalyzer
                .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
        if (exception instanceof AccessDeniedException) {
            return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
        }

        exception = (HttpRequestMethodNotSupportedException) throwableAnalyzer
                .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
        if (exception instanceof HttpRequestMethodNotSupportedException) {
            return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
        }

        exception = (UsernameNotFoundException) throwableAnalyzer
                .getFirstThrowableOfType(UsernameNotFoundException.class, causeChain);
        if (exception instanceof UsernameNotFoundException) {
            return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
        }

        // 不包含上述异常则服务器内部错误
        return handleOAuth2Exception(new HealthyOauthException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
    }

    private ResponseEntity<SimpleResponse> handleOAuth2Exception(OAuth2Exception e) throws IOException {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }

        SimpleResponse simpleResponse = new SimpleResponse(e.getMessage());

        return new ResponseEntity<SimpleResponse>(simpleResponse, headers, HttpStatus.valueOf(status));
    }
}
package com.healthy.security.server.handler.exception;

import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

public class HealthyOauthException extends OAuth2Exception {

    public HealthyOauthException(String msg, Throwable t) {
        super(msg, t);
    }

    public HealthyOauthException(String msg) {
        super(msg);
    }
}
package com.healthy.security.server;

import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * 认证服务器配置
 */
@Configuration
@EnableAuthorizationServer
public class HealthyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //  ...省略

    @Autowired
    private WebResponseExceptionTranslator healthyResponseExceptionTranslator;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .exceptionTranslator(healthyResponseExceptionTranslator);
        }
    
    //  ...省略
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值