Search in sources :

Example 21 with UsernamePasswordCredentials

use of org.pac4j.core.credentials.UsernamePasswordCredentials in project pac4j by pac4j.

the class PropertiesConfigFactoryTests method test.

@Test
public void test() {
    final Map<String, String> properties = new HashMap<>();
    properties.put(FACEBOOK_ID, ID);
    properties.put(FACEBOOK_SECRET, SECRET);
    properties.put(TWITTER_ID, ID);
    properties.put(TWITTER_SECRET, SECRET);
    properties.put(CAS_LOGIN_URL, CALLBACK_URL);
    properties.put(CAS_PROTOCOL, CasProtocol.CAS20.toString());
    properties.put(SAML_KEYSTORE_PASSWORD, PASSWORD);
    properties.put(SAML_PRIVATE_KEY_PASSWORD, PASSWORD);
    properties.put(SAML_KEYSTORE_PATH, PATH);
    properties.put(SAML_IDENTITY_PROVIDER_METADATA_PATH, PATH);
    properties.put(SAML_DESTINATION_BINDING_TYPE, SAMLConstants.SAML2_REDIRECT_BINDING_URI);
    properties.put(SAML_KEYSTORE_ALIAS, VALUE);
    properties.put(OIDC_ID, ID);
    properties.put(OIDC_SECRET, SECRET);
    properties.put(OIDC_DISCOVERY_URI, CALLBACK_URL);
    properties.put(OIDC_USE_NONCE, "true");
    properties.put(OIDC_PREFERRED_JWS_ALGORITHM, "RS384");
    properties.put(OIDC_MAX_CLOCK_SKEW, "60");
    properties.put(OIDC_CLIENT_AUTHENTICATION_METHOD, "CLIENT_SECRET_POST");
    properties.put(OIDC_CUSTOM_PARAM_KEY + "1", KEY);
    properties.put(OIDC_CUSTOM_PARAM_VALUE + "1", VALUE);
    properties.put(CAS_LOGIN_URL.concat(".1"), LOGIN_URL);
    properties.put(CAS_PROTOCOL.concat(".1"), CasProtocol.CAS30.toString());
    properties.put(OIDC_TYPE.concat(".1"), "google");
    properties.put(OIDC_ID.concat(".1"), ID);
    properties.put(OIDC_SECRET.concat(".1"), SECRET);
    properties.put(ANONYMOUS, "whatever the value");
    properties.put(FORMCLIENT_LOGIN_URL, LOGIN_URL);
    properties.put(FORMCLIENT_AUTHENTICATOR, "testUsernamePassword");
    properties.put(INDIRECTBASICAUTH_AUTHENTICATOR.concat(".2"), "testUsernamePassword");
    properties.put(LDAP_TYPE, "direct");
    properties.put(LDAP_URL, "ldap://localhost:" + PORT);
    properties.put(LDAP_USE_SSL, "false");
    properties.put(LDAP_USE_START_TLS, "false");
    properties.put(LDAP_DN_FORMAT, CN + "=%s," + BASE_PEOPLE_DN);
    properties.put(LDAP_USERS_DN, BASE_PEOPLE_DN);
    properties.put(LDAP_PRINCIPAL_ATTRIBUTE_ID, CN);
    properties.put(LDAP_ATTRIBUTES, SN + "," + ROLE);
    properties.put(FORMCLIENT_LOGIN_URL.concat(".2"), PAC4J_BASE_URL);
    properties.put(FORMCLIENT_AUTHENTICATOR.concat(".2"), "ldap");
    properties.put(SPRING_ENCODER_TYPE.concat(".4"), "standard");
    properties.put(SPRING_ENCODER_STANDARD_SECRET.concat(".4"), SALT);
    properties.put(DB_JDBC_URL, "jdbc:h2:mem:test");
    properties.put(DB_USERNAME, Pac4jConstants.USERNAME);
    properties.put(DB_PASSWORD, Pac4jConstants.PASSWORD);
    properties.put(DB_USERNAME_ATTRIBUTE, Pac4jConstants.USERNAME);
    properties.put(DB_USER_PASSWORD_ATTRIBUTE, Pac4jConstants.PASSWORD);
    properties.put(DB_ATTRIBUTES, FIRSTNAME);
    properties.put(DB_PASSWORD_ENCODER, "encoder.spring.4");
    properties.put(INDIRECTBASICAUTH_AUTHENTICATOR.concat(".5"), "db");
    properties.put(REST_URL.concat(".3"), PAC4J_BASE_URL);
    properties.put(DIRECTBASICAUTH_AUTHENTICATOR.concat(".7"), "rest.3");
    LdapServer ldapServer = null;
    try {
        ldapServer = new LdapServer();
        ldapServer.start();
        new DbServer();
        final PropertiesConfigFactory factory = new PropertiesConfigFactory(CALLBACK_URL, properties);
        final Config config = factory.build();
        final Clients clients = config.getClients();
        assertEquals(13, clients.getClients().size());
        final FacebookClient fbClient = (FacebookClient) clients.findClient("FacebookClient");
        assertEquals(ID, fbClient.getKey());
        assertEquals(SECRET, fbClient.getSecret());
        assertNotNull(clients.findClient("AnonymousClient"));
        final TwitterClient twClient = (TwitterClient) clients.findClient("TwitterClient");
        assertEquals(ID, twClient.getKey());
        assertEquals(SECRET, twClient.getSecret());
        final CasClient casClient = (CasClient) clients.findClient("CasClient");
        assertEquals(CALLBACK_URL, casClient.getConfiguration().getLoginUrl());
        assertEquals(CasProtocol.CAS20, casClient.getConfiguration().getProtocol());
        final SAML2Client saml2client = (SAML2Client) clients.findClient("SAML2Client");
        assertNotNull(saml2client);
        final SAML2ClientConfiguration saml2Config = saml2client.getConfiguration();
        assertEquals(SAMLConstants.SAML2_REDIRECT_BINDING_URI, saml2Config.getDestinationBindingType());
        assertEquals(VALUE, saml2Config.getKeyStoreAlias());
        final OidcClient oidcClient = (OidcClient) clients.findClient("OidcClient");
        assertNotNull(oidcClient);
        assertEquals(ClientAuthenticationMethod.CLIENT_SECRET_POST.toString(), oidcClient.getConfiguration().getClientAuthenticationMethod().toString().toLowerCase());
        final CasClient casClient1 = (CasClient) clients.findClient("CasClient.1");
        assertEquals(CasProtocol.CAS30, casClient1.getConfiguration().getProtocol());
        final GoogleOidcClient googleOidcClient = (GoogleOidcClient) clients.findClient("GoogleOidcClient.1");
        googleOidcClient.init();
        assertEquals(ID, googleOidcClient.getConfiguration().getClientId());
        assertEquals(SECRET, googleOidcClient.getConfiguration().getSecret());
        assertEquals("https://accounts.google.com/.well-known/openid-configuration", googleOidcClient.getConfiguration().getDiscoveryURI());
        assertEquals(CALLBACK_URL + "?client_name=GoogleOidcClient.1", googleOidcClient.getCallbackUrlResolver().compute(googleOidcClient.getUrlResolver(), googleOidcClient.getCallbackUrl(), googleOidcClient.getName(), MockWebContext.create()));
        final FormClient formClient = (FormClient) clients.findClient("FormClient");
        assertEquals(LOGIN_URL, formClient.getLoginUrl());
        assertTrue(formClient.getAuthenticator() instanceof SimpleTestUsernamePasswordAuthenticator);
        final FormClient formClient2 = (FormClient) clients.findClient("FormClient.2");
        assertEquals(PAC4J_BASE_URL, formClient2.getLoginUrl());
        assertTrue(formClient2.getAuthenticator() instanceof LdapProfileService);
        final LdapProfileService ldapAuthenticator = (LdapProfileService) formClient2.getAuthenticator();
        final UsernamePasswordCredentials ldapCredentials = new UsernamePasswordCredentials(GOOD_USERNAME, PASSWORD);
        ldapAuthenticator.validate(ldapCredentials, MockWebContext.create());
        assertNotNull(ldapCredentials.getUserProfile());
        final IndirectBasicAuthClient indirectBasicAuthClient = (IndirectBasicAuthClient) clients.findClient("IndirectBasicAuthClient.2");
        assertEquals("authentication required", indirectBasicAuthClient.getRealmName());
        assertTrue(indirectBasicAuthClient.getAuthenticator() instanceof SimpleTestUsernamePasswordAuthenticator);
        final IndirectBasicAuthClient indirectBasicAuthClient2 = (IndirectBasicAuthClient) clients.findClient("IndirectBasicAuthClient.5");
        assertTrue(indirectBasicAuthClient2.getAuthenticator() instanceof DbProfileService);
        final DbProfileService dbAuthenticator = (DbProfileService) indirectBasicAuthClient2.getAuthenticator();
        assertNotNull(dbAuthenticator);
        final UsernamePasswordCredentials dbCredentials = new UsernamePasswordCredentials(GOOD_USERNAME, PASSWORD);
        dbAuthenticator.validate(dbCredentials, MockWebContext.create());
        assertNotNull(dbCredentials.getUserProfile());
        final DirectBasicAuthClient directBasicAuthClient = (DirectBasicAuthClient) clients.findClient("DirectBasicAuthClient.7");
        assertNotNull(directBasicAuthClient);
        final RestAuthenticator restAuthenticator = (RestAuthenticator) directBasicAuthClient.getAuthenticator();
        assertEquals(PAC4J_BASE_URL, restAuthenticator.getUrl());
    } finally {
        if (ldapServer != null) {
            ldapServer.stop();
        }
    }
}
Also used : TwitterClient(org.pac4j.oauth.client.TwitterClient) HashMap(java.util.HashMap) Config(org.pac4j.core.config.Config) FacebookClient(org.pac4j.oauth.client.FacebookClient) FormClient(org.pac4j.http.client.indirect.FormClient) SAML2ClientConfiguration(org.pac4j.saml.client.SAML2ClientConfiguration) GoogleOidcClient(org.pac4j.oidc.client.GoogleOidcClient) DirectBasicAuthClient(org.pac4j.http.client.direct.DirectBasicAuthClient) Clients(org.pac4j.core.client.Clients) RestAuthenticator(org.pac4j.http.credentials.authenticator.RestAuthenticator) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) LdapServer(org.pac4j.ldap.test.tools.LdapServer) OidcClient(org.pac4j.oidc.client.OidcClient) GoogleOidcClient(org.pac4j.oidc.client.GoogleOidcClient) DbProfileService(org.pac4j.sql.profile.service.DbProfileService) DbServer(org.pac4j.sql.test.tools.DbServer) SAML2Client(org.pac4j.saml.client.SAML2Client) CasClient(org.pac4j.cas.client.CasClient) SimpleTestUsernamePasswordAuthenticator(org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator) LdapProfileService(org.pac4j.ldap.profile.service.LdapProfileService) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) Test(org.junit.Test)

Example 22 with UsernamePasswordCredentials

use of org.pac4j.core.credentials.UsernamePasswordCredentials in project pac4j by pac4j.

the class CasRestClientIT method internalTestRestForm.

private void internalTestRestForm(final Authenticator authenticator) {
    final CasRestFormClient client = new CasRestFormClient();
    client.setConfiguration(getConfig());
    client.setAuthenticator(authenticator);
    final MockWebContext context = MockWebContext.create();
    context.addRequestParameter(client.getUsernameParameter(), USER);
    context.addRequestParameter(client.getPasswordParameter(), USER);
    final UsernamePasswordCredentials credentials = client.getCredentials(context);
    final CasRestProfile profile = client.getUserProfile(credentials, context);
    assertEquals(USER, profile.getId());
    assertNotNull(profile.getTicketGrantingTicketId());
    final TokenCredentials casCreds = client.requestServiceTicket(PAC4J_BASE_URL, profile, context);
    final CasProfile casProfile = client.validateServiceTicket(PAC4J_BASE_URL, casCreds, context);
    assertNotNull(casProfile);
    assertEquals(USER, casProfile.getId());
    assertTrue(casProfile.getAttributes().size() > 0);
}
Also used : CasProfile(org.pac4j.cas.profile.CasProfile) MockWebContext(org.pac4j.core.context.MockWebContext) CasRestProfile(org.pac4j.cas.profile.CasRestProfile) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) TokenCredentials(org.pac4j.core.credentials.TokenCredentials)

Example 23 with UsernamePasswordCredentials

use of org.pac4j.core.credentials.UsernamePasswordCredentials 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 24 with UsernamePasswordCredentials

use of org.pac4j.core.credentials.UsernamePasswordCredentials in project cas by apereo.

the class OidcPrivateKeyJwtAuthenticator method validate.

@Override
public void validate(final Credentials creds, final WebContext webContext, final SessionStore sessionStore) {
    val credentials = (UsernamePasswordCredentials) creds;
    val registeredService = verifyCredentials(credentials, webContext);
    if (registeredService == null) {
        LOGGER.warn("Unable to verify credentials");
        return;
    }
    val clientId = registeredService.getClientId();
    val audience = casProperties.getServer().getPrefix().concat('/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.ACCESS_TOKEN_URL);
    val keys = OidcJsonWebKeyStoreUtils.getJsonWebKeySet(registeredService, applicationContext, Optional.of(OidcJsonWebKeyUsage.SIGNING));
    keys.ifPresent(Unchecked.consumer(jwks -> jwks.getJsonWebKeys().forEach(jsonWebKey -> {
        val consumer = new JwtConsumerBuilder().setVerificationKey(jsonWebKey.getKey()).setRequireSubject().setExpectedSubject(clientId).setRequireJwtId().setRequireExpirationTime().setExpectedIssuer(true, clientId).setExpectedAudience(true, audience).build();
        determineUserProfile(credentials, consumer);
    })));
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) Unchecked(org.jooq.lambda.Unchecked) CommonProfile(org.pac4j.core.profile.CommonProfile) SneakyThrows(lombok.SneakyThrows) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) WebContext(org.pac4j.core.context.WebContext) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) OidcJsonWebKeyStoreUtils(org.apereo.cas.oidc.jwks.OidcJsonWebKeyStoreUtils) Optional(java.util.Optional) Credentials(org.pac4j.core.credentials.Credentials) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) Algorithm(com.nimbusds.jose.Algorithm) OidcJsonWebKeyUsage(org.apereo.cas.oidc.jwks.OidcJsonWebKeyUsage) ServicesManager(org.apereo.cas.services.ServicesManager) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 25 with UsernamePasswordCredentials

use of org.pac4j.core.credentials.UsernamePasswordCredentials in project cas by apereo.

the class ECPSamlIdPProfileHandlerController method extractBasicAuthenticationCredential.

private Credential extractBasicAuthenticationCredential(final HttpServletRequest request, final HttpServletResponse response) {
    val extractor = new BasicAuthExtractor();
    val webContext = new JEEContext(request, response);
    val credentialsResult = extractor.extract(webContext, configurationContext.getSessionStore());
    if (credentialsResult.isPresent()) {
        val credentials = (UsernamePasswordCredentials) credentialsResult.get();
        LOGGER.debug("Received basic authentication ECP request from credentials [{}]", credentials);
        return new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
    }
    return null;
}
Also used : lombok.val(lombok.val) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) JEEContext(org.pac4j.core.context.JEEContext) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Aggregations

UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)80 lombok.val (lombok.val)34 JEEContext (org.pac4j.core.context.JEEContext)24 CommonProfile (org.pac4j.core.profile.CommonProfile)22 Test (org.junit.Test)21 Test (org.junit.jupiter.api.Test)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)20 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)20 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)10 BasicAuthExtractor (org.pac4j.core.credentials.extractor.BasicAuthExtractor)9 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)6 Map (java.util.Map)5 MockWebContext (org.pac4j.core.context.MockWebContext)5 UsernamePasswordCredential (org.apereo.cas.authentication.credential.UsernamePasswordCredential)4 CredentialsException (org.pac4j.core.exception.CredentialsException)4 ArrayList (java.util.ArrayList)3 WebContext (org.pac4j.core.context.WebContext)3