use of org.pac4j.core.credentials.UsernamePasswordCredentials in project civiform by seattle-uat.
the class ApiAuthenticatorTest method validate_invalidKeyId.
@Test
public void validate_invalidKeyId() {
String rawCredentials = "wrong" + ":" + secret;
assertBadCredentialsException(buildFakeRequest(rawCredentials), new UsernamePasswordCredentials("wrong", secret), "API key does not exist: wrong");
}
use of org.pac4j.core.credentials.UsernamePasswordCredentials in project civiform by seattle-uat.
the class ApiAuthenticator method validate.
/**
* Authenticates that an API request has a valid API key and is from a permitted IP address.
* Throws a {@link BadCredentialsException} if not, causing a status-only HTTP response 401. The
* exception messages are included in the server logs to aid in debugging and monitoring for
* malicious use.
*/
@Override
public void validate(Credentials rawCredentials, WebContext context, SessionStore sessionStore) {
if (!(rawCredentials instanceof UsernamePasswordCredentials)) {
throw new RuntimeException("ApiAuthenticator must receive UsernamePasswordCredentials.");
}
// The terms "username" and "password" here may look a bit odd since API requests are not
// associated with user accounts but rather API keys. They're used here because pac4j's
// built-in support for basic auth uses those terms to identify the components of the
// basic auth credentials. In this sense, the API key ID is the "username" and the secret
// is the "password". An API key itself can be thought of as the "user account".
UsernamePasswordCredentials credentials = (UsernamePasswordCredentials) rawCredentials;
String keyId = credentials.getUsername();
// Cache the API key for quick lookup in the controller, also for subsequent requests.
// We intentionally cache the empty optional rather than throwing here so that subsequent
// requests with the invalid key do not put pressure on the database.
Optional<ApiKey> maybeApiKey = apiKeyService.get().findByKeyIdWithCache(keyId);
if (!maybeApiKey.isPresent()) {
throwUnauthorized(context, "API key does not exist: " + keyId);
}
ApiKey apiKey = maybeApiKey.get();
if (apiKey.isRetired()) {
throwUnauthorized(context, "API key is retired: " + keyId);
}
if (apiKey.expiredAfter(Instant.now())) {
throwUnauthorized(context, "API key is expired: " + keyId);
}
SubnetUtils allowedSubnet = new SubnetUtils(apiKey.getSubnet());
// Setting this to true includes the network and broadcast addresses.
// I.e. /31 and /32 will not be considered included in the subnetwork
// if this is false.
allowedSubnet.setInclusiveHostCount(true);
if (!allowedSubnet.getInfo().isInRange(context.getRemoteAddr())) {
throwUnauthorized(context, String.format("IP %s not in allowed range for key ID: %s", context.getRemoteAddr(), keyId));
}
String saltedCredentialsSecret = apiKeyService.get().salt(credentials.getPassword());
if (!saltedCredentialsSecret.equals(apiKey.getSaltedKeySecret())) {
throwUnauthorized(context, "Invalid secret for key ID: " + keyId);
}
}
use of org.pac4j.core.credentials.UsernamePasswordCredentials in project cas by apereo.
the class OAuth20Utils method getClientIdAndClientSecret.
/**
* Gets client id and client secret.
*
* @param webContext the web context
* @param sessionStore the session store
* @return the client id and client secret
*/
public static Pair<String, String> getClientIdAndClientSecret(final WebContext webContext, final SessionStore sessionStore) {
val extractor = new BasicAuthExtractor();
val upcResult = extractor.extract(webContext, sessionStore);
if (upcResult.isPresent()) {
val upc = (UsernamePasswordCredentials) upcResult.get();
return Pair.of(upc.getUsername(), upc.getPassword());
}
val clientId = getRequestParameter(webContext, OAuth20Constants.CLIENT_ID).map(String::valueOf).orElse(StringUtils.EMPTY);
val clientSecret = getRequestParameter(webContext, OAuth20Constants.CLIENT_SECRET).map(String::valueOf).orElse(StringUtils.EMPTY);
return Pair.of(clientId, clientSecret);
}
use of org.pac4j.core.credentials.UsernamePasswordCredentials in project cas by apereo.
the class ECPProfileHandlerController method extractBasicAuthenticationCredential.
private Credential extractBasicAuthenticationCredential(final HttpServletRequest request, final HttpServletResponse response) {
try {
final BasicAuthExtractor extractor = new BasicAuthExtractor(this.getClass().getSimpleName());
final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
final UsernamePasswordCredentials credentials = extractor.extract(webContext);
if (credentials != null) {
LOGGER.debug("Received basic authentication ECP request from credentials [{}]", credentials);
return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
}
} catch (final Exception e) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
use of org.pac4j.core.credentials.UsernamePasswordCredentials in project cas by apereo.
the class OidcIntrospectionEndpointController method handlePostRequest.
/**
* Handle post request.
*
* @param request the request
* @param response the response
* @return the response entity
*/
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, value = { '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.INTROSPECTION_URL })
public ResponseEntity<OidcIntrospectionAccessTokenResponse> handlePostRequest(final HttpServletRequest request, final HttpServletResponse response) {
try {
final CredentialsExtractor<UsernamePasswordCredentials> authExtractor = new BasicAuthExtractor();
final UsernamePasswordCredentials credentials = authExtractor.extract(Pac4jUtils.getPac4jJ2EContext(request, response));
if (credentials == null) {
throw new IllegalArgumentException("No credentials are provided to verify introspection on the access token");
}
final OAuthRegisteredService service = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, credentials.getUsername());
if (validateIntrospectionRequest(service, credentials, request)) {
final String accessToken = StringUtils.defaultIfBlank(request.getParameter(OAuth20Constants.ACCESS_TOKEN), request.getParameter(OAuth20Constants.TOKEN));
LOGGER.debug("Located access token [{}] in the request", accessToken);
final AccessToken ticket = this.centralAuthenticationService.getTicket(accessToken, AccessToken.class);
if (ticket != null) {
return createIntrospectionResponse(service, ticket);
}
}
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<>(HttpStatus.OK);
}
Aggregations