是否可以本地化 Spring Oauth2 错误消息?尤其是 InvalidGrantException 和 UsernameNotFoundException 的错误消息。
问问题
929 次
1 回答
0
也许这为时已晚,但我会把我的答案留在这里,以便其他人感兴趣。
据我所知,Spring OAuth2 中没有内置的国际化功能(如果我错了,请纠正我)。但是,Spring 允许我们扩展默认实现以启动它。我猜有两种可能的方法:
1.后端
将服务器上的错误消息国际化并将它们返回给 API。这需要语言环境解析(例如标题语言环境解析)
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;
}
}
将自定义令牌授予者注册到您的授权服务器:
@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
}
于 2017-07-13T07:55:16.650 回答