Search in sources :

Example 6 with CredentialsException

use of org.pac4j.core.exception.CredentialsException in project pac4j by pac4j.

the class SimpleTestDigestAuthenticator method validate.

@Override
public void validate(final TokenCredentials credentials, final WebContext context) {
    if (credentials == null) {
        throw new CredentialsException("No credential");
    }
    if (!(credentials instanceof DigestCredentials)) {
        throw new CredentialsException("Unsupported credentials type " + credentials.getClass());
    }
    DigestCredentials digestCredentials = (DigestCredentials) credentials;
    String username = digestCredentials.getUsername();
    if (CommonHelper.isBlank(username)) {
        throw new CredentialsException("Username cannot be blank");
    }
    String token = credentials.getToken();
    if (CommonHelper.isBlank(token)) {
        throw new CredentialsException("Token cannot be blank");
    }
    CommonProfile profile = new CommonProfile();
    profile.setId(username);
    credentials.setUserProfile(profile);
}
Also used : DigestCredentials(org.pac4j.http.credentials.DigestCredentials) CommonProfile(org.pac4j.core.profile.CommonProfile) CredentialsException(org.pac4j.core.exception.CredentialsException)

Example 7 with CredentialsException

use of org.pac4j.core.exception.CredentialsException in project pac4j by pac4j.

the class DigestAuthExtractor method extract.

/**
 * Extracts digest Authorization header components.
 * As per RFC 2617 :
 * username is the user's name in the specified realm
 * qop is quality of protection
 * uri is the request uri
 * response is the client response
 * nonce is a server-specified data string which should be uniquely generated
 *   each time a 401 response is made
 * cnonce is the client nonce
 * nc is the nonce count
 * If in the Authorization header it is not specified a username and response, we throw CredentialsException because
 * the client uses an username and a password to authenticate. response is just a MD5 encoded value
 * based on user provided password and RFC 2617 digest authentication encoding rules
 * @param context the current web context
 * @return the Digest credentials
 */
@Override
public DigestCredentials extract(WebContext context) {
    final TokenCredentials credentials = this.extractor.extract(context);
    if (credentials == null) {
        return null;
    }
    String token = credentials.getToken();
    Map<String, String> valueMap = parseTokenValue(token);
    String username = valueMap.get("username");
    String response = valueMap.get("response");
    if (CommonHelper.isBlank(username) || CommonHelper.isBlank(response)) {
        throw new CredentialsException("Bad format of the digest auth header");
    }
    String realm = valueMap.get("realm");
    String nonce = valueMap.get("nonce");
    String uri = valueMap.get("uri");
    String cnonce = valueMap.get("cnonce");
    String nc = valueMap.get("nc");
    String qop = valueMap.get("qop");
    String method = context.getRequestMethod();
    return new DigestCredentials(response, method, username, realm, nonce, uri, cnonce, nc, qop);
}
Also used : DigestCredentials(org.pac4j.http.credentials.DigestCredentials) CredentialsException(org.pac4j.core.exception.CredentialsException) TokenCredentials(org.pac4j.core.credentials.TokenCredentials)

Example 8 with CredentialsException

use of org.pac4j.core.exception.CredentialsException in project pac4j by pac4j.

the class DirectCasClient method retrieveCredentials.

@Override
protected TokenCredentials retrieveCredentials(final WebContext context) {
    init();
    try {
        String callbackUrl = callbackUrlResolver.compute(urlResolver, context.getFullRequestURL(), getName(), context);
        final String loginUrl = configuration.computeFinalLoginUrl(context);
        final TokenCredentials credentials = getCredentialsExtractor().extract(context);
        if (credentials == null) {
            // redirect to the login page
            final String redirectionUrl = CommonUtils.constructRedirectUrl(loginUrl, CasConfiguration.SERVICE_PARAMETER, callbackUrl, configuration.isRenew(), false);
            logger.debug("redirectionUrl: {}", redirectionUrl);
            throw HttpAction.redirect(context, redirectionUrl);
        }
        // clean url from ticket parameter
        callbackUrl = CommonHelper.substringBefore(callbackUrl, "?" + CasConfiguration.TICKET_PARAMETER + "=");
        callbackUrl = CommonHelper.substringBefore(callbackUrl, "&" + CasConfiguration.TICKET_PARAMETER + "=");
        final CasAuthenticator casAuthenticator = new CasAuthenticator(configuration, getName(), urlResolver, callbackUrlResolver, callbackUrl);
        casAuthenticator.init();
        casAuthenticator.validate(credentials, context);
        return credentials;
    } catch (CredentialsException e) {
        logger.error("Failed to retrieve or validate CAS credentials", e);
        return null;
    }
}
Also used : CasAuthenticator(org.pac4j.cas.credentials.authenticator.CasAuthenticator) CredentialsException(org.pac4j.core.exception.CredentialsException) TokenCredentials(org.pac4j.core.credentials.TokenCredentials)

Example 9 with CredentialsException

use of org.pac4j.core.exception.CredentialsException in project cas by apereo.

the class OAuth20UsernamePasswordAuthenticator method validate.

@Override
public void validate(final Credentials credentials, final WebContext webContext, final SessionStore sessionStore) throws CredentialsException {
    try {
        val upc = (UsernamePasswordCredentials) credentials;
        val casCredential = new UsernamePasswordCredential(upc.getUsername(), upc.getPassword());
        val clientIdAndSecret = OAuth20Utils.getClientIdAndClientSecret(webContext, this.sessionStore);
        if (StringUtils.isBlank(clientIdAndSecret.getKey())) {
            throw new CredentialsException("No client credentials could be identified in this request");
        }
        val clientId = clientIdAndSecret.getKey();
        val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, clientId);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
        val clientSecret = clientIdAndSecret.getRight();
        if (!OAuth20Utils.checkClientSecret(registeredService, clientSecret, registeredServiceCipherExecutor)) {
            throw new CredentialsException("Client Credentials provided is not valid for registered service: " + Objects.requireNonNull(registeredService).getName());
        }
        val redirectUri = webContext.getRequestParameter(OAuth20Constants.REDIRECT_URI).map(String::valueOf).orElse(StringUtils.EMPTY);
        val service = StringUtils.isNotBlank(redirectUri) ? this.webApplicationServiceFactory.createService(redirectUri) : null;
        val authenticationResult = authenticationSystemSupport.finalizeAuthenticationTransaction(service, casCredential);
        if (authenticationResult == null) {
            throw new CredentialsException("Could not authenticate the provided credentials");
        }
        val authentication = authenticationResult.getAuthentication();
        val principal = authentication.getPrincipal();
        val context = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(service).principal(principal).build();
        val attributes = Objects.requireNonNull(registeredService).getAttributeReleasePolicy().getAttributes(context);
        val profile = new CommonProfile();
        val id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service, registeredService);
        LOGGER.debug("Created profile id [{}]", id);
        profile.setId(id);
        profile.addAttributes((Map) attributes);
        LOGGER.debug("Authenticated user profile [{}]", profile);
        credentials.setUserProfile(profile);
    } catch (final Exception e) {
        throw new CredentialsException("Cannot login user using CAS internal authentication", e);
    }
}
Also used : lombok.val(lombok.val) CommonProfile(org.pac4j.core.profile.CommonProfile) CredentialsException(org.pac4j.core.exception.CredentialsException) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) CredentialsException(org.pac4j.core.exception.CredentialsException) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 10 with CredentialsException

use of org.pac4j.core.exception.CredentialsException in project cas by apereo.

the class OAuth20RefreshTokenAuthenticator method validateCredentials.

@Override
protected void validateCredentials(final UsernamePasswordCredentials credentials, final OAuthRegisteredService registeredService, final WebContext context, final SessionStore sessionStore) {
    val token = credentials.getPassword();
    LOGGER.trace("Received refresh token [{}] for authentication", token);
    val refreshToken = getTicketRegistry().getTicket(token, OAuth20RefreshToken.class);
    val clientId = credentials.getUsername();
    if (refreshToken == null || refreshToken.isExpired() || !StringUtils.equals(refreshToken.getClientId(), clientId)) {
        LOGGER.error("Refresh token [{}] is either not found in the ticket registry, has expired or is not related to the client [{}]", token, clientId);
        throw new CredentialsException("Invalid token: " + token);
    }
}
Also used : lombok.val(lombok.val) CredentialsException(org.pac4j.core.exception.CredentialsException)

Aggregations

CredentialsException (org.pac4j.core.exception.CredentialsException)20 TokenCredentials (org.pac4j.core.credentials.TokenCredentials)5 CommonProfile (org.pac4j.core.profile.CommonProfile)5 lombok.val (lombok.val)4 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)4 Authentication (org.apereo.cas.authentication.Authentication)2 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)2 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)2 Principal (org.apereo.cas.authentication.principal.Principal)2 Service (org.apereo.cas.authentication.principal.Service)2 RegisteredService (org.apereo.cas.services.RegisteredService)2 OAuthClientProfile (org.apereo.cas.support.oauth.profile.OAuthClientProfile)2 OAuthUserProfile (org.apereo.cas.support.oauth.profile.OAuthUserProfile)2 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)2 DigestCredentials (org.pac4j.http.credentials.DigestCredentials)2 EncryptionMethod (com.nimbusds.jose.EncryptionMethod)1 JOSEException (com.nimbusds.jose.JOSEException)1 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)1 JWEHeader (com.nimbusds.jose.JWEHeader)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1