I've write small code to generate tokens and use that token instead of username and password and it seems working better.
I generate tokens for 8 hours and store in database. When next time user logs in I check the current token and if expired I generate new one.
public class FeatureServiceTokenService {
private static final Logger LOGGER = Logger.getLogger(ArcgisTokenService.class.getName());
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper = new ObjectMapper();
public FeatureServiceTokenService() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
restTemplate = new RestTemplate();
restTemplate.setMessageConverters(messageConverters);
}
public TokenData generateToken(String username, String password, int expireMinutes) {
LOGGER.log(Level.INFO, "Generating token for {0} minutes", expireMinutes);
TokenData tokenData = null;
try {
MultiValueMap<String, String> postParams = new LinkedMultiValueMap<>();
postParams.add("username", username);
postParams.add("password", password);
postParams.add("client", RequestConstants.CLIENT_TYPE_REQUEST_IP);
postParams.add("expiration", "" + expireMinutes);
postParams.add("f", RequestConstants.FORMAT_JSON);
ResponseEntity<String> response = restTemplate.postForEntity("http://xxx.xxx.xxx.xxx:6080/arcgis/tokens/", postParams, String.class);
LOGGER.log(Level.INFO, "Token response: {0}", response);
if (response.getStatusCode() == HttpStatus.OK) {
tokenData = objectMapper.readValue(response.getBody(), TokenData.class);
}
} catch (IOException | RestClientException e) {
LOGGER.log(Level.SEVERE, null, e);
}
return tokenData;
}
}
And supply the token by:
userCredentials = new UserCredentials();
userCredentials.setTokenServiceUrl(astConfig.ARCGIS_SERVICE_TOKEN_SERVICE_URL);
userCredentials.setAuthenticationType(UserCredentials.AuthenticationType.TOKEN);
userCredentials.setUserToken(tokenData.getToken(), tokenData.getExpires(), "http://xxx.xxx.xxx.xxx:6080/arcgis/tokens/");