微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Spring Oauth2 – 自定义异常处理程序

Spring Security基于Oauth2的身份验证中,当客户端发送需要刷新的访问令牌时,DefaultTokenServices类会抛出InvalidTokenException(参见第235行):

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/main/java/org/springframework/security/oauth2/provider/token/DefaultTokenServices.java

发生这种情况时的输出是这样的:

{"error":"invalid_token","error_description":"Invalid access token: a0cb5ab9-7281-46bd-a9a2-796a04a906c9"
}

我想改变这个输出,但我迷路了.其他一些答案建议设置一个自定义的exceptionRenderer,但这也不起作用,我的自定义异常渲染器在这些情况下永远不会被调用.

还有一种称为异常翻译器的东西,但无论如何它们都没有被称为.

我的春季配置的一部分:

ecurity.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
    ecurity.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
      ecurity.oauth2.provider.error.OAuth2AccessDeniedHandler" >
 

异常渲染器:

public class MyExceptionRenderer implements OAuth2ExceptionRenderer {

@Override
public void handlehttpentityResponse(httpentitystem.out.println("Thrown exception");
}

}

我还添加一个自定义的异常映射器,它应该获得所有异常,但是因为我假设它的另一个servlet,在这种情况下这不起作用吗?

@Provider
public class GenericExceptionMapper implements ExceptionMapperstem.out.println("MAPPING EXCEPTION");
    return Response.status(200).entity().build();
}
}

我可以捕获AuthenticationException的情况,但不能捕获任何InvalidTokenExceptions.

对此有何帮助? Spring实际上在哪里捕获此InvalidTokenException以及如何设置它以便我可以提供自定义输出

最佳答案
InvalidTokenException扩展ClientAuthenticationException.因此,您可以通过扩展ClientAuthenticationException并抛出此而不是InvalidTokenException来创建自己的异常

public class CustomException extends ClientAuthenticationException {

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

    public CustomException(String msg) {
        super(msg);
    }
    @Override
    public String getoAuth2ErrorCode() {
        return "my_custom_exception";
    }
}

喜欢

throw new CustomException("Invalid access token: " + accesstokenValue);

在InvalidTokenException引发的错误

 {"error":"invalid_token","error_description":"Invalid access token: a0cb5ab9-7281-46bd-a9a2-796a04a906c9"}

invalid_token由InvalidTokenException和无效访问令牌的getoAuth2ErrorCode()方法返回:a0cb5ab9-7281-46bd-a9a2-796a04a906c9是抛出异常时给出的消息.

如果你扔了

 throw new CustomException("This is my custom exception");

错误显示

{"error":"my_custom_exception","error_description":"This is my custom exception"}

my_custom_exception来自CustomException的getoAuth2ErrorCode().

原文地址:https://www.jb51.cc/spring/432575.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐