Java Spring Oauth异常消息中的国际化

Java Spring Oauth异常消息中的国际化,java,spring,spring-security,spring-security-oauth2,Java,Spring,Spring Security,Spring Security Oauth2,是否可以本地化Spring Oauth2错误消息?特别是InvalidGrantException和UsernameNotFoundException的错误消息。也许这已经太晚了,但我会在这里留下我的答案,也许其他人对此感兴趣 据我所知,SpringOAuth2中没有内置的国际化特性。如果我错了,请纠正我。然而,Spring允许我们扩展默认实现来启动它。我想有两种可能的方法: 一,。后端 国际化服务器上的错误消息并将其返回到API。这需要区域设置解析,例如标题区域设置解析 二,。后端+前端 将其

是否可以本地化Spring Oauth2错误消息?特别是InvalidGrantException和UsernameNotFoundException的错误消息。

也许这已经太晚了,但我会在这里留下我的答案,也许其他人对此感兴趣

据我所知,SpringOAuth2中没有内置的国际化特性。如果我错了,请纠正我。然而,Spring允许我们扩展默认实现来启动它。我想有两种可能的方法:

一,。后端

国际化服务器上的错误消息并将其返回到API。这需要区域设置解析,例如标题区域设置解析

二,。后端+前端

将其他错误代码附加到响应中,前端需要将它们映射到本地化消息中

其思想是实现一个自定义TokenGranter,并将AuthenticationException转换为您自己的异常,例如身份验证时的InvalidGrantException

下面的示例为不同类型的无效\u grant appoache 2创建不同的错误代码:

将自定义令牌授予者注册到授权服务器:

@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenGranter(new CustomTokenGranter (...));
    }
}
答复示例:

{
    "error": "invalid_grant",
    "error_description": "User is disabled",
    "error_code": "01235"
}
如果您想采用方法1,可以执行类似于方法2的操作,并通过从RequestContextHolder获取servlet请求来解析您的区域设置:

RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
    HttpServletRequest sRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
    Locale locale = sRequest.getLocale(); ...
    // Resolve your error messages here from above obtained locale
}

我怀疑在残疾人的情况下不是这样的。UsernameNotFoundException是Spring安全核心的一部分,因此它可能有一些i18n。这可能完全取决于你想将它们本地化到哪里——如果它在日志文件中,你可能运气不好。@DaveSyer我愿意接受建议。如果我能在DB级别对它们进行本地化,我对此持开放态度。我不确定你所说的DB是什么意思。谁将使用您的本地化数据?@DaveSyer DB作为数据库中的本地化抽象。我的数据的消费者是最终用户。在这种情况下,我希望确保在出现错误时提供本地化的翻译文本。用户通常不会看到安全异常消息。具体情况是什么?
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
    HttpServletRequest sRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
    Locale locale = sRequest.getLocale(); ...
    // Resolve your error messages here from above obtained locale
}