java - Internationalization in Spring Oauth exception messages -
is possible have spring oauth2 error messages localized? error messages invalidgrantexception , usernamenotfoundexception.
maybe late, gonna leave answer here maybe else interested.
as far know, there no builtin internationalization feature in spring oauth2 (please correct me if wrong). however, spring lets extends default implementations up. there 2 possible approaches i'd guess:
1. backend
internationalize error messages on server , return them api. requires locale resolving (e.g. header locale resolving)
2. backend + frontend
attach additional error codes response , frontend need map them localized message.
the idea implement custom tokengranter , translate authenticationexception own exception (e.g. invalidgrantexception) on authenticating.
example below creates different error codes different types of 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; } }
register custom token granter authorization server:
@enableauthorizationserver public class authorizationserverconfiguration extends authorizationserverconfigureradapter { @override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { endpoints.tokengranter(new customtokengranter (...)); } }
example response:
{ "error": "invalid_grant", "error_description": "user disabled", "error_code": "01235" }
if want take approach #1, can similar approach #2 , resolve locale obtaining servlet request requestcontextholder:
requestattributes requestattributes = requestcontextholder.getrequestattributes(); if (requestattributes != null && requestattributes instanceof servletrequestattributes) { httpservletrequest srequest = ((servletrequestattributes) requestattributes).getrequest(); locale locale = srequest.getlocale(); ... // resolve error messages here above obtained locale }
Comments
Post a Comment