Search in sources :

Example 1 with BasicCredentialMetaData

use of org.apereo.cas.authentication.metadata.BasicCredentialMetaData in project cas by apereo.

the class CoreAuthenticationTestUtils method getAuthenticationBuilder.

public static AuthenticationBuilder getAuthenticationBuilder(final Principal principal, final Map<Credential, ? extends AuthenticationHandler> handlers, final Map<String, List<Object>> attributes) {
    val builder = new DefaultAuthenticationBuilder(principal).setAttributes(attributes);
    handlers.forEach((credential, handler) -> {
        builder.addSuccess(handler.getName(), new DefaultAuthenticationHandlerExecutionResult(handler, new BasicCredentialMetaData(credential)));
        builder.addCredential(new BasicCredentialMetaData(credential));
    });
    return builder;
}
Also used : lombok.val(lombok.val) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData)

Example 2 with BasicCredentialMetaData

use of org.apereo.cas.authentication.metadata.BasicCredentialMetaData in project cas by apereo.

the class CoreAuthenticationTestUtils method getAuthentication.

public static Authentication getAuthentication(final Principal principal, final Map<String, List<Object>> attributes, final ZonedDateTime authnDate) {
    val handler = new SimpleTestUsernamePasswordAuthenticationHandler();
    val meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
    return new DefaultAuthenticationBuilder(principal).addCredential(meta).setAuthenticationDate(authnDate).addSuccess(handler.getName(), new DefaultAuthenticationHandlerExecutionResult(handler, meta)).setAttributes(attributes).build();
}
Also used : lombok.val(lombok.val) SimpleTestUsernamePasswordAuthenticationHandler(org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler) UsernamePasswordCredential(org.apereo.cas.authentication.credential.UsernamePasswordCredential) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData)

Example 3 with BasicCredentialMetaData

use of org.apereo.cas.authentication.metadata.BasicCredentialMetaData in project cas by apereo.

the class OAuth20DefaultCasAuthenticationBuilder method build.

@Override
public Authentication build(final UserProfile profile, final OAuthRegisteredService registeredService, final WebContext context, final Service service) {
    val attrs = new HashMap<>(profile.getAttributes());
    val profileAttributes = CoreAuthenticationUtils.convertAttributeValuesToMultiValuedObjects(attrs);
    val newPrincipal = principalFactory.createPrincipal(profile.getId(), profileAttributes);
    LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
    val authenticator = profile.getClass().getCanonicalName();
    val metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
    val handlerResult = new DefaultAuthenticationHandlerExecutionResult(authenticator, metadata, newPrincipal, new ArrayList<>(0));
    val scopes = OAuth20Utils.getRequestedScopes(context);
    val state = context.getRequestParameter(OAuth20Constants.STATE).map(String::valueOf).or(() -> OAuth20Utils.getRequestParameter(context, OAuth20Constants.STATE)).orElse(StringUtils.EMPTY);
    val nonce = context.getRequestParameter(OAuth20Constants.NONCE).map(String::valueOf).or(() -> OAuth20Utils.getRequestParameter(context, OAuth20Constants.NONCE)).orElse(StringUtils.EMPTY);
    LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce);
    val builder = DefaultAuthenticationBuilder.newInstance();
    if (profile instanceof BasicUserProfile) {
        val authenticationAttributes = ((BasicUserProfile) profile).getAuthenticationAttributes();
        builder.addAttributes(authenticationAttributes);
    }
    builder.addAttribute("permissions", new LinkedHashSet<>(profile.getPermissions())).addAttribute("roles", new LinkedHashSet<>(profile.getRoles())).addAttribute("scopes", scopes).addAttribute(OAuth20Constants.STATE, state).addAttribute(OAuth20Constants.NONCE, nonce).addAttribute(OAuth20Constants.CLIENT_ID, registeredService.getClientId()).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now(ZoneOffset.UTC)).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
    context.getRequestParameter(OAuth20Constants.ACR_VALUES).ifPresent(value -> builder.addAttribute(OAuth20Constants.ACR_VALUES, value));
    return builder.build();
}
Also used : lombok.val(lombok.val) LinkedHashSet(java.util.LinkedHashSet) HashMap(java.util.HashMap) BasicIdentifiableCredential(org.apereo.cas.authentication.credential.BasicIdentifiableCredential) BasicUserProfile(org.pac4j.core.profile.BasicUserProfile) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData)

Example 4 with BasicCredentialMetaData

use of org.apereo.cas.authentication.metadata.BasicCredentialMetaData in project cas by apereo.

the class DefaultAuthenticationManager method authenticateInternal.

/**
 * Authenticate internal authentication builder.
 *
 * @param transaction the transaction
 * @return the authentication builder
 * @throws AuthenticationException the authentication exception
 */
protected AuthenticationBuilder authenticateInternal(final AuthenticationTransaction transaction) throws AuthenticationException {
    val credentials = transaction.getCredentials();
    LOGGER.debug("Authentication credentials provided for this transaction are [{}]", credentials);
    if (credentials.isEmpty()) {
        LOGGER.error("Resolved authentication handlers for this transaction are empty");
        throw new AuthenticationException("Resolved credentials for this transaction are empty");
    }
    val builder = new DefaultAuthenticationBuilder(NullPrincipal.getInstance());
    credentials.forEach(cred -> builder.addCredential(new BasicCredentialMetaData(cred)));
    val handlerSet = this.authenticationEventExecutionPlan.getAuthenticationHandlers(transaction);
    LOGGER.debug("Candidate resolved authentication handlers for this transaction are [{}]", handlerSet);
    try {
        val it = credentials.iterator();
        AuthenticationCredentialsThreadLocalBinder.clearInProgressAuthentication();
        while (it.hasNext()) {
            val credential = it.next();
            LOGGER.debug("Attempting to authenticate credential [{}]", credential);
            val itHandlers = handlerSet.iterator();
            var proceedWithNextHandler = true;
            while (proceedWithNextHandler && itHandlers.hasNext()) {
                val handler = itHandlers.next();
                if (handler.supports(credential)) {
                    try {
                        val resolver = getPrincipalResolverLinkedToHandlerIfAny(handler, transaction);
                        LOGGER.debug("Attempting authentication of [{}] using [{}]", credential.getId(), handler.getName());
                        authenticateAndResolvePrincipal(builder, credential, resolver, handler);
                        val authnResult = builder.build();
                        AuthenticationCredentialsThreadLocalBinder.bindInProgress(authnResult);
                        val executionResult = evaluateAuthenticationPolicies(authnResult, transaction, handlerSet);
                        proceedWithNextHandler = !executionResult.isSuccess();
                    } catch (final GeneralSecurityException e) {
                        handleAuthenticationException(e, handler.getName(), builder);
                        proceedWithNextHandler = shouldAuthenticationChainProceedOnFailure(transaction, e);
                    } catch (final Exception e) {
                        LOGGER.error("Authentication has failed. Credentials may be incorrect or CAS cannot " + "find authentication handler that supports [{}] of type [{}]. Examine the configuration to " + "ensure a method of authentication is defined and analyze CAS logs at DEBUG level to trace " + "the authentication event.", credential, credential.getClass().getSimpleName());
                        handleAuthenticationException(e, handler.getName(), builder);
                        proceedWithNextHandler = shouldAuthenticationChainProceedOnFailure(transaction, e);
                    }
                } else {
                    LOGGER.debug("Authentication handler [{}] does not support the credential type [{}].", handler.getName(), credential);
                }
            }
        }
        evaluateFinalAuthentication(builder, transaction, handlerSet);
        return builder;
    } finally {
        AuthenticationCredentialsThreadLocalBinder.clearInProgressAuthentication();
    }
}
Also used : lombok.val(lombok.val) GeneralSecurityException(java.security.GeneralSecurityException) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData) UnresolvedPrincipalException(org.apereo.cas.authentication.exceptions.UnresolvedPrincipalException) GeneralSecurityException(java.security.GeneralSecurityException)

Example 5 with BasicCredentialMetaData

use of org.apereo.cas.authentication.metadata.BasicCredentialMetaData in project cas by apereo.

the class DefaultCentralAuthenticationServiceMockitoTests method prepareNewCAS.

@BeforeEach
public void prepareNewCAS() {
    this.authentication = mock(Authentication.class);
    when(this.authentication.getAuthenticationDate()).thenReturn(ZonedDateTime.now(ZoneOffset.UTC));
    val metadata = new BasicCredentialMetaData(RegisteredServiceTestUtils.getCredentialsWithSameUsernameAndPassword("principal"));
    val successes = new HashMap<String, AuthenticationHandlerExecutionResult>();
    successes.put("handler1", new DefaultAuthenticationHandlerExecutionResult(mock(AuthenticationHandler.class), metadata));
    when(this.authentication.getCredentials()).thenReturn(List.of(metadata));
    when(this.authentication.getSuccesses()).thenReturn(successes);
    when(this.authentication.getPrincipal()).thenReturn(PrincipalFactoryUtils.newPrincipalFactory().createPrincipal(PRINCIPAL));
    val tgtRootMock = createRootTicketGrantingTicket();
    val service1 = getService(SVC1_ID);
    val stMock = createMockServiceTicket(ST_ID, service1);
    val tgtMock = createMockTicketGrantingTicket(TGT_ID, stMock, false, tgtRootMock, new ArrayList<>());
    when(tgtMock.getProxiedBy()).thenReturn(getService("proxiedBy"));
    stMock.setTicketGrantingTicket(tgtMock);
    val authnListMock = mock(List.class);
    /*
         * Size is required to be 2, so that
         * we can simulate proxying capabilities
         */
    when(authnListMock.size()).thenReturn(2);
    when(authnListMock.toArray()).thenReturn(new Object[] { this.authentication, this.authentication });
    when(authnListMock.get(anyInt())).thenReturn(this.authentication);
    when(tgtMock.getChainedAuthentications()).thenReturn(authnListMock);
    val service2 = getService(SVC2_ID);
    val stMock2 = createMockServiceTicket(ST2_ID, service2);
    val tgtMock2 = createMockTicketGrantingTicket(TGT2_ID, stMock2, false, tgtRootMock, authnListMock);
    stMock2.setTicketGrantingTicket(tgtMock2);
    mockTicketRegistry(stMock, tgtMock, stMock2, tgtMock2);
    val smMock = getServicesManager(service1, service2);
    val factory = getTicketFactory();
    val authenticationRequestServiceSelectionStrategies = new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy());
    val enforcer = mock(AuditableExecution.class);
    when(enforcer.execute(any())).thenReturn(new AuditableExecutionResult());
    val applicationContext = new StaticApplicationContext();
    applicationContext.refresh();
    val context = CentralAuthenticationServiceContext.builder().applicationContext(applicationContext).ticketRegistry(ticketRegMock).servicesManager(smMock).ticketFactory(factory).lockRepository(LockRepository.asDefault()).authenticationServiceSelectionPlan(authenticationRequestServiceSelectionStrategies).authenticationPolicyFactory(new AcceptAnyAuthenticationPolicyFactory()).principalFactory(PrincipalFactoryUtils.newPrincipalFactory()).cipherExecutor(CipherExecutor.noOpOfStringToString()).registeredServiceAccessStrategyEnforcer(enforcer).serviceMatchingStrategy(new DefaultServiceMatchingStrategy(smMock)).build();
    this.cas = new DefaultCentralAuthenticationService(context);
}
Also used : lombok.val(lombok.val) AcceptAnyAuthenticationPolicyFactory(org.apereo.cas.authentication.policy.AcceptAnyAuthenticationPolicyFactory) DefaultAuthenticationServiceSelectionStrategy(org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy) HashMap(java.util.HashMap) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) DefaultAuthenticationServiceSelectionPlan(org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) DefaultServiceMatchingStrategy(org.apereo.cas.authentication.principal.DefaultServiceMatchingStrategy) Authentication(org.apereo.cas.authentication.Authentication) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

lombok.val (lombok.val)21 BasicCredentialMetaData (org.apereo.cas.authentication.metadata.BasicCredentialMetaData)21 DefaultAuthenticationHandlerExecutionResult (org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult)12 UsernamePasswordCredential (org.apereo.cas.authentication.credential.UsernamePasswordCredential)8 SimpleTestUsernamePasswordAuthenticationHandler (org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler)7 FailedLoginException (javax.security.auth.login.FailedLoginException)6 Test (org.junit.jupiter.api.Test)6 GeneralSecurityException (java.security.GeneralSecurityException)3 HashMap (java.util.HashMap)3 DefaultAuthenticationBuilder (org.apereo.cas.authentication.DefaultAuthenticationBuilder)3 BasicIdentifiableCredential (org.apereo.cas.authentication.credential.BasicIdentifiableCredential)3 DefaultMessageDescriptor (org.apereo.cas.DefaultMessageDescriptor)2 SpnegoCredential (org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential)2 LinkedHashMap (java.util.LinkedHashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)1 Type1Message (jcifs.ntlmssp.Type1Message)1 Type2Message (jcifs.ntlmssp.Type2Message)1 Type3Message (jcifs.ntlmssp.Type3Message)1 NtlmPasswordAuthentication (jcifs.smb.NtlmPasswordAuthentication)1