Search in sources :

Example 46 with UsernamePasswordCredentials

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");
}
Also used : UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) Test(org.junit.Test)

Example 47 with UsernamePasswordCredentials

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);
    }
}
Also used : SubnetUtils(org.apache.commons.net.util.SubnetUtils) ApiKey(models.ApiKey) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 48 with UsernamePasswordCredentials

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);
}
Also used : lombok.val(lombok.val) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 49 with UsernamePasswordCredentials

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;
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) WebContext(org.pac4j.core.context.WebContext) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 50 with UsernamePasswordCredentials

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);
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) ResponseEntity(org.springframework.http.ResponseEntity) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)91 lombok.val (lombok.val)35 Test (org.junit.Test)25 JEEContext (org.pac4j.jee.context.JEEContext)24 CommonProfile (org.pac4j.core.profile.CommonProfile)23 Test (org.junit.jupiter.api.Test)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)21 MockSessionStore (org.pac4j.core.context.session.MockSessionStore)17 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)10 BasicAuthExtractor (org.pac4j.core.credentials.extractor.BasicAuthExtractor)10 OAuth20DefaultCode (org.apereo.cas.ticket.code.OAuth20DefaultCode)8 HardTimeoutExpirationPolicy (org.apereo.cas.ticket.expiration.HardTimeoutExpirationPolicy)8 HashMap (java.util.HashMap)7 SimpleTestUsernamePasswordAuthenticator (org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator)7 Map (java.util.Map)6 WebContext (org.pac4j.core.context.WebContext)5 UsernamePasswordCredential (org.apereo.cas.authentication.credential.UsernamePasswordCredential)4 CasRestProfile (org.pac4j.cas.profile.CasRestProfile)4 CredentialsException (org.pac4j.core.exception.CredentialsException)4