Skip to content

Commit

Permalink
fix: avoid using @PostConstruct
Browse files Browse the repository at this point in the history
  • Loading branch information
restfulhead committed Jun 11, 2019
1 parent cb2bb89 commit fbfd7c6
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 82 deletions.
1 change: 0 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@
</plugin>
<plugin>
<artifactId>maven-scm-plugin</artifactId>
<version>1.9.4</version>
<configuration>
<tag>${project.version}</tag>
</configuration>
Expand Down
36 changes: 15 additions & 21 deletions src/main/java/org/sonatype/nexus/plugins/okta/OktaAuthRealm.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,12 @@
import org.eclipse.sisu.Description;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.UserManager;
import org.sonatype.nexus.security.user.UserNotFoundException;

import org.sonatype.nexus.plugins.okta.client.OktaAuthClient;
import org.sonatype.nexus.plugins.okta.client.OktaAuthClientException;
import org.sonatype.nexus.plugins.okta.client.OktaAuthClientExceptionSeverity;
import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.UserManager;
import org.sonatype.nexus.security.user.UserNotFoundException;

@Singleton
@Named
Expand All @@ -40,19 +39,14 @@ public class OktaAuthRealm extends AuthorizingRealm
public static final String NAME = OktaAuthRealm.class.getName();

private final OktaAuthClient client;
private UserManager userManager;
private final UserManager userManager;

@Inject
public OktaAuthRealm(final OktaAuthClient client, final UserManager userManager)
{
this.client = Objects.requireNonNull(client);
this.userManager = Objects.requireNonNull(userManager);
}

@Override
protected void onInit()
{
super.onInit();
LOG.info("Okta Auth Realm for {} initialized...", this.client.getConfig().getOktaOrgUrl());
}

Expand All @@ -66,7 +60,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken t
}

final UsernamePasswordToken t = (UsernamePasswordToken) token;
String password = new String(t.getPassword());
final String password = new String(t.getPassword());

LOG.info("Authenticating with Okta for user {}", t.getUsername());

Expand All @@ -75,7 +69,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken t
client.authn(t.getUsername(), password);
return new SimpleAuthenticationInfo(t.getUsername(), token.getCredentials(), getName());

} catch (OktaAuthClientException ex)
} catch (final OktaAuthClientException ex)
{
if (OktaAuthClientExceptionSeverity.INFO.equals(ex.getSeverity()))
{
Expand All @@ -89,7 +83,7 @@ protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken t
LOG.error("Authentication for '" + t.getUsername() + "' was not successful: " + ex.getMessage());
throw new AccountException(ex.getMessage(), ex);
}
} catch (Exception ex)
} catch (final Exception ex)
{
LOG.error("Unexpected authentication error: " + ex.getMessage(), ex);
throw new AuthenticationException(ex.getMessage(), ex);
Expand All @@ -99,27 +93,27 @@ protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken t
}

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals)
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals)
{
Object principal = principals.getPrimaryPrincipal();
final Object principal = principals.getPrimaryPrincipal();
if (!(principal instanceof String))
{
LOG.error("Expected principal of type String but was " + principal == null ? "null"
LOG.error("Expected principal of type String but was {}", principal == null ? "null"
: principal.getClass().getName());
return null;
}
Set<String> roles = new HashSet<String>();

final Set<String> roles = new HashSet<>();
try {
for (RoleIdentifier roleIdentifier : userManager.getUser((String) principal).getRoles()) {
for (final RoleIdentifier roleIdentifier : userManager.getUser((String) principal).getRoles()) {
roles.add(roleIdentifier.getRoleId());
}
}
catch (UserNotFoundException e) {
catch (final UserNotFoundException e) {
throw new AuthorizationException("User for principals: " + principals.getPrimaryPrincipal()
+ " could not be found.", e);
}

return new SimpleAuthorizationInfo(roles);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,28 @@
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.sonatype.nexus.plugins.okta.client.dto.OktaErrorResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ApiHttpClientImpl implements ApiHttpClient
{
private static final Logger LOG = LoggerFactory.getLogger(ApiHttpClientImpl.class);
private ObjectMapper mapper;
private CloseableHttpClient client;

private final ObjectMapper mapper;
private final CloseableHttpClient client;

public ApiHttpClientImpl()
{
this(HttpClients.createDefault());
}

public ApiHttpClientImpl(final CloseableHttpClient client)
{
this(client, new ObjectMapper());
}

public ApiHttpClientImpl(final CloseableHttpClient client, final ObjectMapper mapper)
{
super();
Expand All @@ -45,15 +45,16 @@ public ApiHttpClientImpl(final CloseableHttpClient client, final ObjectMapper ma
}

@Override
public <T> T sendPostRequest(String uri, Object requestBody, Class<T> responseClazz)
public <T> T sendPostRequest(final String uri, final Object requestBody, final Class<T> responseClazz)
{
try
{
final String json = mapper.writeValueAsString(requestBody);
if (!LOG.isDebugEnabled())
{
LOG.debug("Sending POST request to {} with request body {}", uri, json);
} else
}
else
{
LOG.info("Sending POST request to {}", uri);
}
Expand All @@ -70,39 +71,43 @@ public <T> T sendPostRequest(String uri, Object requestBody, Class<T> responseCl

if (statusCode > 399)
{
OktaAuthClientExceptionSeverity severity = statusCode > 499 ? ERROR : INFO;
final OktaAuthClientExceptionSeverity severity = statusCode > 499 ? ERROR : INFO;
throw new OktaAuthClientException(severity, readResponseBody(uri, response, OktaErrorResponse.class));
}

final String responseStr = EntityUtils.toString(response.getEntity());
if (LOG.isDebugEnabled())
{
LOG.debug("Retrieved {} response from {} with response body: {}", statusCode, uri, responseStr);
} else
}
else
{
LOG.info("Retrieved {} response from {}", statusCode, uri);
}

final T responseObj = mapper.readValue(responseStr, responseClazz);
return responseObj;
}
} catch (IOException e)
}
catch (final IOException e)
{
throw new RuntimeException(e.getMessage(), e);
}
}

public String asStrOrEmpty(Object obj)

@Override
public String asStrOrEmpty(final Object obj)
{
try
{
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e)
}
catch (final JsonProcessingException e)
{
return "";
}
}

private <T> T readResponseBody(final String uri, final CloseableHttpResponse response, final Class<T> responseClazz)
{
if (response.getEntity() != null)
Expand All @@ -119,19 +124,18 @@ private <T> T readResponseBody(final String uri, final CloseableHttpResponse res

final T responseObj = mapper.readValue(responseStr, responseClazz);
return responseObj;
} catch (ParseException | IOException e)
}
catch (ParseException | IOException e)
{
final StatusLine statusLine = response.getStatusLine();
final String errMsg = "Unable to parse response from " + uri + " with code " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase() + ": " + responseStr;
throw new OktaAuthClientException(ERROR, errMsg, e);
}
} else
{
final StatusLine statusLine = response.getStatusLine();
final String errMsg = "No response body provided by " + uri + " with code " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase();
throw new OktaAuthClientException(ERROR, errMsg);
}
final StatusLine statusLine = response.getStatusLine();
final String errMsg = "No response body provided by " + uri + " with code " + statusLine.getStatusCode() + " - "
+ statusLine.getReasonPhrase();
throw new OktaAuthClientException(ERROR, errMsg);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import static org.sonatype.nexus.plugins.okta.client.OktaAuthClientExceptionSeverity.INFO;
import static org.sonatype.nexus.plugins.okta.client.OktaAuthClientExceptionSeverity.WARN;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
Expand All @@ -12,7 +11,6 @@
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.sonatype.nexus.plugins.okta.client.dto.OktaAuthRequest;
import org.sonatype.nexus.plugins.okta.client.dto.OktaAuthRequestVerifyFactor;
import org.sonatype.nexus.plugins.okta.client.dto.OktaAuthResponse;
Expand All @@ -36,6 +34,7 @@ public OktaAuthClient()
public OktaAuthClient(final OktaAuthClientConfig config)
{
this.config = config;
client = new ApiHttpClientImpl();
}

public OktaAuthClient(final ApiHttpClient client, final OktaAuthClientConfig config)
Expand All @@ -44,14 +43,6 @@ public OktaAuthClient(final ApiHttpClient client, final OktaAuthClientConfig con
this.config = config;
}

@PostConstruct
public void init()
{
if (client == null) {
client = new ApiHttpClientImpl();
}
}

public OktaAuthClientConfig getConfig()
{
return config;
Expand All @@ -78,13 +69,12 @@ public OktaAuthResponse authn(final String username, final String password)
"Authentication appears to be successful, but no session token was found.");
}
return response;
} else
{
throw new OktaAuthClientException(INFO, "Authentication was not successful");
}

throw new OktaAuthClientException(INFO, "Authentication was not successful");
}

protected OktaAuthResponse handleMfaChallenge(OktaAuthResponse response)
protected OktaAuthResponse handleMfaChallenge(final OktaAuthResponse response)
{
if (response == null || response.getEmbedded() == null || CollectionUtils.isEmpty(response.getEmbedded().getFactors()))
{
Expand All @@ -93,7 +83,7 @@ protected OktaAuthResponse handleMfaChallenge(OktaAuthResponse response)
}

OktaAuthResponseEmbeddedFactor selectedFactor = null;
for (OktaAuthResponseEmbeddedFactor factor : response.getEmbedded().getFactors())
for (final OktaAuthResponseEmbeddedFactor factor : response.getEmbedded().getFactors())
{
if ("push".equalsIgnoreCase(factor.getFactorType()))
{
Expand All @@ -112,16 +102,16 @@ protected OktaAuthResponse handleMfaChallenge(OktaAuthResponse response)
return verifyMfa(response.getStateToken(), selectedFactor);
}

protected OktaAuthResponse verifyMfa(String stateToken, OktaAuthResponseEmbeddedFactor factor)
protected OktaAuthResponse verifyMfa(final String stateToken, final OktaAuthResponseEmbeddedFactor factor)
{
if (factor == null || factor.getLinks() == null || factor.getLinks().getVerify() == null
|| StringUtils.isBlank(factor.getLinks().getVerify().getHref()))
{
throw new OktaAuthClientException(WARN, "Expected to find link for verification on factor " + client.asStrOrEmpty(factor));
}
String verifyLink = factor.getLinks().getVerify().getHref();
OktaAuthRequestVerifyFactor body = new OktaAuthRequestVerifyFactor(stateToken);
OktaAuthResponse verificationResponse = client.sendPostRequest(verifyLink, body, OktaAuthResponse.class);
final String verifyLink = factor.getLinks().getVerify().getHref();
final OktaAuthRequestVerifyFactor body = new OktaAuthRequestVerifyFactor(stateToken);
final OktaAuthResponse verificationResponse = client.sendPostRequest(verifyLink, body, OktaAuthResponse.class);

if (verificationResponse == null || verificationResponse.getLinks() == null
|| verificationResponse.getLinks().getNext() == null
Expand All @@ -131,13 +121,13 @@ protected OktaAuthResponse verifyMfa(String stateToken, OktaAuthResponseEmbedded
"Expected to find link to poll for push notification: " + client.asStrOrEmpty(verificationResponse));
}

int pollDelay = config.getMfaPollDelay();
int pollMaxRetries = config.getMfaPollMaxRetries();
final int pollDelay = config.getMfaPollDelay();
final int pollMaxRetries = config.getMfaPollMaxRetries();
return pollForPushNotification(stateToken, verificationResponse.getLinks().getNext().getHref(), pollDelay, pollMaxRetries,
1);
}

protected OktaAuthResponse pollForPushNotification(String stateToken, String pollLink, int delay, int maxRetries, int tryNo)
protected OktaAuthResponse pollForPushNotification(final String stateToken, final String pollLink, final int delay, final int maxRetries, final int tryNo)
{
if (tryNo >= maxRetries)
{
Expand All @@ -148,13 +138,13 @@ protected OktaAuthResponse pollForPushNotification(String stateToken, String pol
try
{
Thread.sleep(delay);
} catch (InterruptedException e)
} catch (final InterruptedException e)
{
LOG.warn(e.getMessage(), e); // ignore
}

OktaAuthRequestVerifyFactor body = new OktaAuthRequestVerifyFactor(stateToken);
OktaAuthResponse response = client.sendPostRequest(pollLink, body, OktaAuthResponse.class);
final OktaAuthRequestVerifyFactor body = new OktaAuthRequestVerifyFactor(stateToken);
final OktaAuthResponse response = client.sendPostRequest(pollLink, body, OktaAuthResponse.class);
if ("SUCCESS".equals(response.getStatus()))
{
return response;
Expand All @@ -173,5 +163,5 @@ protected OktaAuthResponse pollForPushNotification(String stateToken, String pol
}
}


}
Loading

0 comments on commit fbfd7c6

Please sign in to comment.