当前位置:   article > 正文

Spring security oauth2 ExceptionTranslationFilter所抛异常处理_oauth2 抛出的异常 怎么捕获

oauth2 抛出的异常 怎么捕获

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  1. package com.healthy.security.server.handler;
  2. import com.healthy.security.core.support.SimpleResponse;
  3. import com.healthy.security.server.handler.exception.HealthyOauthException;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.http.HttpHeaders;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.http.ResponseEntity;
  8. import org.springframework.security.core.AuthenticationException;
  9. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  10. import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
  11. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  12. import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
  13. import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
  14. import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
  15. import org.springframework.security.web.util.ThrowableAnalyzer;
  16. import org.springframework.stereotype.Component;
  17. import org.springframework.web.HttpRequestMethodNotSupportedException;
  18. import java.io.IOException;
  19. import java.nio.file.AccessDeniedException;
  20. /**
  21. * healthy translator that converts exceptions into {@link OAuth2Exception}s. The output matches the OAuth 2.0
  22. * specification in terms of error response format and HTTP status code.
  23. */
  24. @Slf4j
  25. @Component("healthyResponseExceptionTranslator")
  26. public class HealthyResponseExceptionTranslator implements WebResponseExceptionTranslator<SimpleResponse> {
  27. private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();
  28. @Override
  29. public ResponseEntity<SimpleResponse> translate(Exception e) throws Exception {
  30. // Try to extract a SpringSecurityException from the stacktrace
  31. Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
  32. // 异常栈获取 OAuth2Exception 异常
  33. Exception exception = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
  34. // 异常栈中有OAuth2Exception
  35. if (exception != null) {
  36. return handleOAuth2Exception((OAuth2Exception) exception);
  37. }
  38. exception = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class,
  39. causeChain);
  40. if (exception != null) {
  41. return handleOAuth2Exception(new HealthyOauthException(e.getMessage(), e));
  42. }
  43. exception = (AccessDeniedException) throwableAnalyzer
  44. .getFirstThrowableOfType(AccessDeniedException.class, causeChain);
  45. if (exception instanceof AccessDeniedException) {
  46. return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
  47. }
  48. exception = (HttpRequestMethodNotSupportedException) throwableAnalyzer
  49. .getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
  50. if (exception instanceof HttpRequestMethodNotSupportedException) {
  51. return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
  52. }
  53. exception = (UsernameNotFoundException) throwableAnalyzer
  54. .getFirstThrowableOfType(UsernameNotFoundException.class, causeChain);
  55. if (exception instanceof UsernameNotFoundException) {
  56. return handleOAuth2Exception(new HealthyOauthException(exception.getMessage(), exception));
  57. }
  58. // 不包含上述异常则服务器内部错误
  59. return handleOAuth2Exception(new HealthyOauthException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));
  60. }
  61. private ResponseEntity<SimpleResponse> handleOAuth2Exception(OAuth2Exception e) throws IOException {
  62. int status = e.getHttpErrorCode();
  63. HttpHeaders headers = new HttpHeaders();
  64. headers.set("Cache-Control", "no-store");
  65. headers.set("Pragma", "no-cache");
  66. if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
  67. headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
  68. }
  69. SimpleResponse simpleResponse = new SimpleResponse(e.getMessage());
  70. return new ResponseEntity<SimpleResponse>(simpleResponse, headers, HttpStatus.valueOf(status));
  71. }
  72. }
  1. package com.healthy.security.server.handler.exception;
  2. import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
  3. public class HealthyOauthException extends OAuth2Exception {
  4. public HealthyOauthException(String msg, Throwable t) {
  5. super(msg, t);
  6. }
  7. public HealthyOauthException(String msg) {
  8. super(msg);
  9. }
  10. }
  1. package com.healthy.security.server;
  2. import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
  3. /**
  4. * 认证服务器配置
  5. */
  6. @Configuration
  7. @EnableAuthorizationServer
  8. public class HealthyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
  9. // ...省略
  10. @Autowired
  11. private WebResponseExceptionTranslator healthyResponseExceptionTranslator;
  12. @Override
  13. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  14. endpoints
  15. .exceptionTranslator(healthyResponseExceptionTranslator);
  16. }
  17. // ...省略
  18. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/277135
推荐阅读
相关标签
  

闽ICP备14008679号