是否可以本地化 Spring Oauth2 错误消息?特别是 InvalidGrantException 和 UsernameNotFoundException 的错误消息。
最佳答案
也许这已经太晚了,但我会在这里留下我的答案,以便其他人感兴趣。
据我所知,Spring OAuth2 中没有内置的国际化功能(如果我错了,请纠正我)。然而,Spring 允许我们扩展默认实现来实现它。我猜想有两种可能的方法:
<强>1。后端
在服务器上国际化您的错误消息并将其返回到 API。这需要区域设置解析(例如 header 区域设置解析)
<强>2。后端+前端
将附加错误代码附加到您的响应中,前端需要将它们映射到本地化消息中。
这个想法是实现一个自定义的 TokenGranter 并将 AuthenticationException 转换为您自己的身份验证异常(例如 InvalidGrantException)。
下面的示例为不同类型的 invalid_grant 创建不同的错误代码(appoache #2):
public class CustomTokenGranter extends AbstractTokenGranter {
private static final String ERROR_CODE_KEY = "error_code";
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
try {
....
authenticationManager.authenticate(...);
} catch (AccountStatusException ase) {
mapAndThrow(ase);
} catch (BadCredentialsException e) {
InvalidGrantException ige = new InvalidGrantException("Bad credentials");
ige.addAdditionalInformation(ERROR_CODE_KEY, "01234");
throw ige;
}
}
private void mapAndThrow(AccountStatusException ase) {
InvalidGrantException ige = new InvalidGrantException(ase.getMessage());
if (ase instanceof DisabledException) {
ige.addAdditionalInformation(ERROR_CODE_KEY, "01235");
} else if (ase instanceof LockedException) {
ige.addAdditionalInformation(ERROR_CODE_KEY, "01236");
} else if (ase instanceof AccountExpiredException) {
ige.addAdditionalInformation(ERROR_CODE_KEY, "01237");
}
// More goes here
throw ige;
}
}
将自定义 token 授予者注册到您的授权服务器:
@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
}
关于java - Spring Oauth 异常消息中的国际化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354435/