Это решения, которые я придумал, выполните вход в систему для следующих случаев использования:
- первоначальный вход в систему
- refre sh срок действия маркера истек
- сеанс истек (устаревший токен)
- сеанс был отключен (вручную, перезапуск службы)
- другое OAuthServiceException выдается во время авторизации
String serverUrl = "http://localhost:8180/auth";
String realm = "share-server";
String clientId = "share-server-service-login";
String clientSecret = "e70752a6-8910-4043-8926-03661f43398c";
String username = "test";
String password = "test";
String tokenUri = serverUrl + "/realms/" + realm + "/protocol/openid-connect/token";
ResourceOwnerGrant grant = new ResourceOwnerGrant(username, password);
AuthSupplier supplier = new AuthSupplier(tokenUri, clientId, clientSecret, grant);
HTTPConduitConfigurer httpConduitConfigurer = new HTTPConduitConfigurer() {
@Override
public void configure(String name, String address, HTTPConduit c) {
// don't do authentication on token URI
if (!tokenUri.equals(address)) {
c.setAuthSupplier(supplier);
}
}
};
Bus bus = BusFactory.getThreadDefaultBus();
bus.setExtension(httpConduitConfigurer, HTTPConduitConfigurer.class);
... REST-Client Code ...
public static class AuthSupplier extends BearerAuthSupplier {
private WebClient webClient = null;
private AccessTokenGrant grant;
public AuthSupplier(String tokenUri, String clientId, String clientSecret, AccessTokenGrant grant) {
grant = grant;
webClient = WebClient.create(tokenUri);
setAccessTokenServiceUri(tokenUri);
setConsumer(new Consumer(clientId, clientSecret));
}
@Override
public String getAuthorization(AuthorizationPolicy authPolicy, URI currentURI, Message message, String fullHeader) {
String authorization = null;
try {
authorization = super.getAuthorization(authPolicy, currentURI, message, fullHeader);
} catch (OAuthServiceException e) {
System.out.println(e.getError().getState() + " " + e.getMessage());
}
if (authorization == null) {
// refresh token expired or session expired (Stale token) or session was logged-out (manually, service-restart), do new login
login();
// try to get authorization again after login
authorization = super.getAuthorization(authPolicy, currentURI, message, null);
}
return authorization;
}
private void login() {
ClientAccessToken accessToken = OAuthClientUtils.getAccessToken(webClient, getConsumer(), grant, false);
setAccessToken(accessToken.getTokenKey());
setRefreshToken(accessToken.getRefreshToken());
}
}