{"id":1417,"date":"2023-03-20T21:43:31","date_gmt":"2023-03-20T13:43:31","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=1417"},"modified":"2023-04-28T21:06:32","modified_gmt":"2023-04-28T13:06:32","slug":"spring-security-oauth2-authentication-server-custom-exception-handling","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/03\/20\/spring-security-oauth2-authentication-server-custom-exception-handling\/","title":{"rendered":"Spring Security OAuth2 \u8ba4\u8bc1\u670d\u52a1\u5668\u81ea\u5b9a\u4e49\u5f02\u5e38\u5904\u7406"},"content":{"rendered":"<p>\u8ba4\u8bc1\u670d\u52a1\u5668\u9ed8\u8ba4\u8fd4\u56de\u7684\u6570\u636e\u683c\u5f0f\u5982\u4e0b\uff1a<\/p>\n<pre><code class=\"language-json\">{\n    &quot;error&quot;: &quot;unsupported_grant_type&quot;,\n    &quot;error_description&quot;: &quot;Unsupported grant type: password1&quot;\n}<\/code><\/pre>\n<p><!-- more --><\/p>\n<p>\u4e0a\u9762\u7684\u8fd4\u56de\u7ed3\u679c\u5f88\u4e0d\u53cb\u597d\uff0c\u800c\u4e14\u524d\u7aef\u4ee3\u7801\u4e5f\u5f88\u96be\u5224\u65ad\u662f\u4ec0\u4e48\u9519\u8bef\uff0c\u6240\u4ee5\u6211\u4eec\u9700\u8981\u5bf9\u8fd4\u56de\u7684\u9519\u8bef\u8fdb\u884c\u7edf\u4e00\u7684\u5f02\u5e38\u5904\u7406<\/p>\n<h2>\u9ed8\u8ba4\u7684\u5f02\u5e38\u5904\u7406\u5668<\/h2>\n<p>\u9ed8\u8ba4\u60c5\u51b5\u662f\u4f7f\u7528<code>WebResponseExceptionTranslator<\/code>\u63a5\u53e3\u7684\u5b9e\u73b0\u7c7b<code>DefaultWebResponseExceptionTranslator<\/code>\u5bf9\u629b\u51fa\u7684\u5f02\u5e38\u8fdb\u884c\u5904\u7406\uff1b\u6240\u4ee5\u53ef\u4ee5\u901a\u8fc7<code>WebResponseExceptionTranslator<\/code>\u63a5\u53e3\u5165\u624b\uff0c\u5b9e\u73b0\u63a5\u53e3\u7684\u65b9\u6cd5\u5bf9\u5f02\u5e38\u8fdb\u884c\u5904\u7406\u3002<\/p>\n<h2>\u5b9a\u4e49\u7ee7\u627fOAuth2Exception\u7684\u5f02\u5e38\u7c7b<\/h2>\n<pre><code class=\"language-java\">\/**\n * @Description: \u5f02\u5e38\u5904\u7406\u7c7b\n * @Package: cn.appblog.security.oauth2.exception.UserOAuth2Exception\n * @Version: 1.0\n *\/\n@JsonSerialize(using = UserOAuth2ExceptionSerializer.class)\npublic class UserOAuth2Exception extends OAuth2Exception {\n    private Integer status = 400;\n\n    public UserOAuth2Exception(String message, Throwable t) {\n        super(message, t);\n        status = ((OAuth2Exception) t).getHttpErrorCode();\n    }\n\n    public UserOAuth2Exception(String message) {\n        super(message);\n    }\n\n    @Override\n    public int getHttpErrorCode() {\n        return status;\n    }\n}<\/code><\/pre>\n<h2>\u5b9a\u4e49\u5e8f\u5217\u5316\u5b9e\u73b0\u7c7b<\/h2>\n<pre><code class=\"language-java\">\/**\n * @Description: \u5e8f\u5217\u5316\u5f02\u5e38\u7c7b\n * @Package: cn.appblog.security.oauth2.exception.BootOAuthExceptionJacksonSerializer\n * @Version: 1.0\n *\/\npublic class UserOAuth2ExceptionSerializer extends StdSerializer&lt;UserOAuth2Exception&gt; {\n\n    protected UserOAuth2ExceptionSerializer() {\n        super(UserOAuth2Exception.class);\n    }\n\n    @Override\n    public void serialize(UserOAuth2Exception e, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException {\n        generator.writeStartObject();\n        generator.writeObjectField(&quot;status&quot;, e.getHttpErrorCode());\n        String message = e.getMessage();\n        if (message != null) {\n            message = HtmlUtils.htmlEscape(message);\n        }\n        generator.writeStringField(&quot;message&quot;, message);\n        if (e.getAdditionalInformation() != null) {\n            for (Map.Entry&lt;String, String&gt; entry : e.getAdditionalInformation().entrySet()) {\n                String key = entry.getKey();\n                String add = entry.getValue();\n                generator.writeStringField(key, add);\n            }\n        }\n        generator.writeEndObject();\n    }\n}<\/code><\/pre>\n<h2>\u81ea\u5b9a\u4e49\u5b9e\u73b0\u5f02\u5e38\u8f6c\u6362\u7c7b<\/h2>\n<pre><code class=\"language-java\">\/**\n * @Description: \u8d44\u6e90\u670d\u52a1\u5668\u5f02\u5e38\u81ea\u5b9a\u4e49\u6355\u83b7\n * @Package: cn.appblog.security.oauth2.exception.OAuth2ServerWebResponseExceptionTranslator\n * @Version: 1.0\n *\/\n@Component\npublic class UserOAuth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {\n    private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();\n\n    @Override\n    public ResponseEntity&lt;OAuth2Exception&gt; translate(Exception e) throws Exception {\n        Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(e);\n        Exception ase = (OAuth2Exception) this.throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);\n        \/\/\u5f02\u5e38\u94fe\u4e2d\u6709OAuth2Exception\u5f02\u5e38\n        if (ase != null) {\n            return this.handleOAuth2Exception((OAuth2Exception) ase);\n        }\n        \/\/\u8eab\u4efd\u9a8c\u8bc1\u76f8\u5173\u5f02\u5e38\n        ase = (AuthenticationException) this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);\n        if (ase != null) {\n            return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.UnauthorizedException(e.getMessage(), e));\n        }\n        \/\/\u5f02\u5e38\u94fe\u4e2d\u5305\u542b\u62d2\u7edd\u8bbf\u95ee\u5f02\u5e38\n        ase = (AccessDeniedException) this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);\n        if (ase instanceof AccessDeniedException) {\n            return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.ForbiddenException(ase.getMessage(), ase));\n        }\n        \/\/\u5f02\u5e38\u94fe\u4e2d\u5305\u542bHttp\u65b9\u6cd5\u8bf7\u6c42\u5f02\u5e38\n        ase = (HttpRequestMethodNotSupportedException) this.throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);\n        if (ase instanceof HttpRequestMethodNotSupportedException) {\n            return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.MethodNotAllowed(ase.getMessage(), ase));\n        }\n        return this.handleOAuth2Exception(new UserOAuth2WebResponseExceptionTranslator.ServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e));\n    }\n\n    private ResponseEntity&lt;OAuth2Exception&gt; handleOAuth2Exception(OAuth2Exception e) throws IOException {\n        int status = e.getHttpErrorCode();\n        HttpHeaders headers = new HttpHeaders();\n        headers.set(&quot;Cache-Control&quot;, &quot;no-store&quot;);\n        headers.set(&quot;Pragma&quot;, &quot;no-cache&quot;);\n        if (status == HttpStatus.UNAUTHORIZED.value() || e instanceof InsufficientScopeException) {\n            headers.set(&quot;WWW-Authenticate&quot;, String.format(&quot;%s %s&quot;, &quot;Bearer&quot;, e.getSummary()));\n        }\n        UserOAuth2Exception exception = new UserOAuth2Exception(e.getMessage(), e);\n        ResponseEntity&lt;OAuth2Exception&gt; response = new ResponseEntity(exception, headers, HttpStatus.valueOf(status));\n        return response;\n    }\n\n    private static class MethodNotAllowed extends OAuth2Exception {\n        public MethodNotAllowed(String msg, Throwable t) {\n            super(msg, t);\n        }\n\n        @Override\n        public String getOAuth2ErrorCode() {\n            return &quot;method_not_allowed&quot;;\n        }\n\n        @Override\n        public int getHttpErrorCode() {\n            return 405;\n        }\n    }\n\n    private static class UnauthorizedException extends OAuth2Exception {\n        public UnauthorizedException(String msg, Throwable t) {\n            super(msg, t);\n        }\n\n        @Override\n        public String getOAuth2ErrorCode() {\n            return &quot;unauthorized&quot;;\n        }\n\n        @Override\n        public int getHttpErrorCode() {\n            return 401;\n        }\n    }\n\n    private static class ServerErrorException extends OAuth2Exception {\n        public ServerErrorException(String msg, Throwable t) {\n            super(msg, t);\n        }\n\n        @Override\n        public String getOAuth2ErrorCode() {\n            return &quot;server_error&quot;;\n        }\n\n        @Override\n        public int getHttpErrorCode() {\n            return 500;\n        }\n    }\n\n    private static class ForbiddenException extends OAuth2Exception {\n        public ForbiddenException(String msg, Throwable t) {\n            super(msg, t);\n        }\n\n        @Override\n        public String getOAuth2ErrorCode() {\n            return &quot;access_denied&quot;;\n        }\n\n        @Override\n        public int getHttpErrorCode() {\n            return 403;\n        }\n    }\n}<\/code><\/pre>\n<h2>\u5c06\u81ea\u5b9a\u4e49\u5f02\u5e38\u5904\u7406\u7c7b\u6dfb\u52a0\u5230\u8ba4\u8bc1\u670d\u52a1\u5668\u914d\u7f6e<\/h2>\n<pre><code class=\"language-java\">\/**\n * @Description: @EnableAuthorizationServer\u6ce8\u89e3\u5f00\u542fOAuth2\u6388\u6743\u670d\u52a1\u673a\u5236\n * @Package: cn.appblog.security.oauth2.config.AuthorizationServerConfigure\n * @Version: 1.0\n *\/\n@Configuration\n@EnableAuthorizationServer\npublic class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {\n\n    @Autowired\n    private WebResponseExceptionTranslator webResponseExceptionTranslator;\n\n    \/**\n     * \u7528\u6765\u914d\u7f6e\u6388\u6743\uff08authorization\uff09\u4ee5\u53ca\u4ee4\u724c\uff08token)\u7684\u8bbf\u95ee\u7aef\u70b9\u548c\u4ee4\u724c\u670d\u52a1\uff08token services\uff09\n     *\/\n    @Override\n    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {\n        ...\n\n        endpoints.exceptionTranslator(webResponseExceptionTranslator);\n\n        ...\n    }\n\n}<\/code><\/pre>\n<p>\u672c\u6587\u8f6c\u8f7d\u53c2\u8003 <a target=\"_blank\" rel=\"noopener\" href=\"https:\/\/blog.csdn.net\/yaomingyang\/column\/info\/41645\" title=\"\u539f\u6587\">\u539f\u6587<\/a> \u5e76\u52a0\u4ee5\u8c03\u8bd5<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u8ba4\u8bc1\u670d\u52a1\u5668\u9ed8\u8ba4\u8fd4\u56de\u7684\u6570\u636e\u683c\u5f0f\u5982\u4e0b\uff1a { &quot;error&quot;: &quot;unsupporte [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[354],"tags":[353],"class_list":["post-1417","post","type-post","status-publish","format-standard","hentry","category-spring-security","tag-oauth2"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1417","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1417"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/1417\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1417"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1417"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1417"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}