Search in sources :

Example 6 with DefaultHandlerResult

use of org.apereo.cas.authentication.DefaultHandlerResult in project cas by apereo.

the class BaseOAuthWrapperController method createAuthentication.

/**
     * Create an authentication from a user profile.
     *
     * @param profile           the given user profile
     * @param registeredService the registered service
     * @param context           the context
     * @param service           the service
     * @return the built authentication
     */
protected Authentication createAuthentication(final UserProfile profile, final RegisteredService registeredService, final J2EContext context, final Service service) {
    final Principal newPrincipal = this.scopeToAttributesFilter.filter(service, this.principalFactory.createPrincipal(profile.getId(), profile.getAttributes()), registeredService, context);
    LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
    final String authenticator = profile.getClass().getCanonicalName();
    final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
    final HandlerResult handlerResult = new DefaultHandlerResult(authenticator, metadata, newPrincipal, new ArrayList<>());
    final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.STATE), StringUtils.EMPTY);
    final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.NONCE), StringUtils.EMPTY);
    LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuthConstants.STATE, state, OAuthConstants.NONCE, nonce);
    final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance().addAttribute("permissions", profile.getPermissions()).addAttribute("roles", profile.getRoles()).addAttribute(OAuthConstants.STATE, state).addAttribute(OAuthConstants.NONCE, nonce).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now()).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
    // Add "other" profile attributes as authentication attributes.
    if (casProperties.getAuthn().getOauth().getAccessToken().isReleaseProtocolAttributes()) {
        profile.getAttributes().forEach((k, v) -> {
            if (!newPrincipal.getAttributes().containsKey(k)) {
                LOGGER.debug("Added attribute [{}] with value [{}] to the authentication", k, v);
                bldr.addAttribute(k, v);
            } else {
                LOGGER.debug("Skipped over attribute [{}] since it's already contained by the principal", k);
            }
        });
    }
    return bldr.build();
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) HandlerResult(org.apereo.cas.authentication.HandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) Principal(org.apereo.cas.authentication.principal.Principal) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Example 7 with DefaultHandlerResult

use of org.apereo.cas.authentication.DefaultHandlerResult in project cas by apereo.

the class KryoTranscoderTests method verifyEncodeDecodeTGTImpl.

@Test
public void verifyEncodeDecodeTGTImpl() throws Exception {
    final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
    final AuthenticationBuilder bldr = new DefaultAuthenticationBuilder(new DefaultPrincipalFactory().createPrincipal("user", new HashMap<>(this.principalAttributes)));
    bldr.setAttributes(new HashMap<>(this.principalAttributes));
    bldr.setAuthenticationDate(ZonedDateTime.now());
    bldr.addCredential(new BasicCredentialMetaData(userPassCredential));
    bldr.addFailure("error", AccountNotFoundException.class);
    bldr.addSuccess("authn", new DefaultHandlerResult(new AcceptUsersAuthenticationHandler(""), new BasicCredentialMetaData(userPassCredential)));
    final TicketGrantingTicket expectedTGT = new TicketGrantingTicketImpl(TGT_ID, RegisteredServiceTestUtils.getService(), null, bldr.build(), new NeverExpiresExpirationPolicy());
    final ServiceTicket ticket = expectedTGT.grantServiceTicket(ST_ID, RegisteredServiceTestUtils.getService(), new NeverExpiresExpirationPolicy(), false, true);
    CachedData result = transcoder.encode(expectedTGT);
    final TicketGrantingTicket resultTicket = (TicketGrantingTicket) transcoder.decode(result);
    assertEquals(expectedTGT, resultTicket);
    result = transcoder.encode(ticket);
    final ServiceTicket resultStTicket = (ServiceTicket) transcoder.decode(result);
    assertEquals(ticket, resultStTicket);
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Credential(org.apereo.cas.authentication.Credential) HttpBasedServiceCredential(org.apereo.cas.authentication.HttpBasedServiceCredential) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) MockServiceTicket(org.apereo.cas.mock.MockServiceTicket) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) CachedData(net.spy.memcached.CachedData) NeverExpiresExpirationPolicy(org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) AcceptUsersAuthenticationHandler(org.apereo.cas.authentication.AcceptUsersAuthenticationHandler) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) Test(org.junit.Test)

Example 8 with DefaultHandlerResult

use of org.apereo.cas.authentication.DefaultHandlerResult in project cas by apereo.

the class OAuth20AccessTokenControllerTests method getAuthentication.

private static Authentication getAuthentication(final Principal principal) {
    final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(principal.getId()));
    final HandlerResult handlerResult = new DefaultHandlerResult(principal.getClass().getCanonicalName(), metadata, principal, new ArrayList<>());
    return DefaultAuthenticationBuilder.newInstance().setPrincipal(principal).setAuthenticationDate(ZonedDateTime.now()).addCredential(metadata).addSuccess(principal.getClass().getCanonicalName(), handlerResult).build();
}
Also used : BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) HandlerResult(org.apereo.cas.authentication.HandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Example 9 with DefaultHandlerResult

use of org.apereo.cas.authentication.DefaultHandlerResult in project cas by apereo.

the class JcifsSpnegoAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final SpnegoCredential spnegoCredential = (SpnegoCredential) credential;
    final java.security.Principal principal;
    final byte[] nextToken;
    if (!this.isNTLMallowed && spnegoCredential.isNtlm()) {
        throw new FailedLoginException("NTLM not allowed");
    }
    try {
        // proceed authentication using jcifs
        synchronized (this) {
            this.authentication.reset();
            LOGGER.debug("Processing SPNEGO authentication");
            this.authentication.process(spnegoCredential.getInitToken());
            principal = this.authentication.getPrincipal();
            LOGGER.debug("Authenticated SPNEGO principal [{}]", principal.getName());
            LOGGER.debug("Retrieving the next token for authentication");
            nextToken = this.authentication.getNextToken();
        }
    } catch (final jcifs.spnego.AuthenticationException e) {
        throw new FailedLoginException(e.getMessage());
    }
    // evaluate jcifs response
    if (nextToken != null) {
        LOGGER.debug("Setting nextToken in credential");
        spnegoCredential.setNextToken(nextToken);
    } else {
        LOGGER.debug("nextToken is null");
    }
    boolean success = false;
    if (principal != null) {
        if (spnegoCredential.isNtlm()) {
            LOGGER.debug("NTLM Credential is valid for user [{}]", principal.getName());
        } else {
            LOGGER.debug("Kerberos Credential is valid for user [{}]", principal.getName());
        }
        spnegoCredential.setPrincipal(getPrincipal(principal.getName(), spnegoCredential.isNtlm()));
        success = true;
    }
    if (!success) {
        throw new FailedLoginException("Principal is null, the processing of the SPNEGO Token failed");
    }
    return new DefaultHandlerResult(this, new BasicCredentialMetaData(credential), spnegoCredential.getPrincipal());
}
Also used : SpnegoCredential(org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential) FailedLoginException(javax.security.auth.login.FailedLoginException) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Example 10 with DefaultHandlerResult

use of org.apereo.cas.authentication.DefaultHandlerResult in project cas by apereo.

the class NtlmAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final SpnegoCredential ntlmCredential = (SpnegoCredential) credential;
    final byte[] src = ntlmCredential.getInitToken();
    final UniAddress dc;
    boolean success = false;
    try {
        if (this.loadBalance) {
            // find the first dc that matches the includepattern
            if (StringUtils.isNotBlank(this.includePattern)) {
                final NbtAddress[] dcs = NbtAddress.getAllByName(this.domainController, NBT_ADDRESS_TYPE, null, null);
                dc = Arrays.stream(dcs).filter(dc2 -> dc2.getHostAddress().matches(this.includePattern)).findFirst().map(UniAddress::new).orElse(null);
            } else {
                dc = new UniAddress(NbtAddress.getByName(this.domainController, NBT_ADDRESS_TYPE, null));
            }
        } else {
            dc = UniAddress.getByName(this.domainController, true);
        }
        final byte[] challenge = SmbSession.getChallenge(dc);
        switch(src[NTLM_TOKEN_TYPE_FIELD_INDEX]) {
            case NTLM_TOKEN_TYPE_ONE:
                LOGGER.debug("Type 1 received");
                final Type1Message type1 = new Type1Message(src);
                final Type2Message type2 = new Type2Message(type1, challenge, null);
                LOGGER.debug("Type 2 returned. Setting next token.");
                ntlmCredential.setNextToken(type2.toByteArray());
                break;
            case NTLM_TOKEN_TYPE_THREE:
                LOGGER.debug("Type 3 received");
                final Type3Message type3 = new Type3Message(src);
                final byte[] lmResponse = type3.getLMResponse() == null ? new byte[0] : type3.getLMResponse();
                final byte[] ntResponse = type3.getNTResponse() == null ? new byte[0] : type3.getNTResponse();
                final NtlmPasswordAuthentication ntlm = new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge, lmResponse, ntResponse);
                LOGGER.debug("Trying to authenticate [{}] with domain controller", type3.getUser());
                try {
                    SmbSession.logon(dc, ntlm);
                    ntlmCredential.setPrincipal(this.principalFactory.createPrincipal(type3.getUser()));
                    success = true;
                } catch (final SmbAuthException sae) {
                    throw new FailedLoginException(sae.getMessage());
                }
                break;
            default:
                LOGGER.debug("Unknown type: [{}]", src[NTLM_TOKEN_TYPE_FIELD_INDEX]);
        }
    } catch (final Exception e) {
        throw new FailedLoginException(e.getMessage());
    }
    if (!success) {
        throw new FailedLoginException();
    }
    return new DefaultHandlerResult(this, new BasicCredentialMetaData(ntlmCredential), ntlmCredential.getPrincipal());
}
Also used : Type2Message(jcifs.ntlmssp.Type2Message) Type3Message(jcifs.ntlmssp.Type3Message) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) PreventedException(org.apereo.cas.authentication.PreventedException) SmbAuthException(jcifs.smb.SmbAuthException) UniAddress(jcifs.UniAddress) Type1Message(jcifs.ntlmssp.Type1Message) SpnegoCredential(org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential) SmbAuthException(jcifs.smb.SmbAuthException) FailedLoginException(javax.security.auth.login.FailedLoginException) NtlmPasswordAuthentication(jcifs.smb.NtlmPasswordAuthentication) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) NbtAddress(jcifs.netbios.NbtAddress)

Aggregations

DefaultHandlerResult (org.apereo.cas.authentication.DefaultHandlerResult)16 BasicCredentialMetaData (org.apereo.cas.authentication.BasicCredentialMetaData)13 FailedLoginException (javax.security.auth.login.FailedLoginException)9 CredentialMetaData (org.apereo.cas.authentication.CredentialMetaData)6 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)5 DefaultAuthenticationBuilder (org.apereo.cas.authentication.DefaultAuthenticationBuilder)4 HandlerResult (org.apereo.cas.authentication.HandlerResult)4 DefaultPrincipalFactory (org.apereo.cas.authentication.principal.DefaultPrincipalFactory)4 AuthenticationBuilder (org.apereo.cas.authentication.AuthenticationBuilder)3 BasicIdentifiableCredential (org.apereo.cas.authentication.BasicIdentifiableCredential)3 GeneralSecurityException (java.security.GeneralSecurityException)2 HashMap (java.util.HashMap)2 X509CertificateCredential (org.apereo.cas.adaptors.x509.authentication.principal.X509CertificateCredential)2 AuthenticationHandler (org.apereo.cas.authentication.AuthenticationHandler)2 HttpBasedServiceCredential (org.apereo.cas.authentication.HttpBasedServiceCredential)2 PreventedException (org.apereo.cas.authentication.PreventedException)2 SimpleTestUsernamePasswordAuthenticationHandler (org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler)2 Principal (org.apereo.cas.authentication.principal.Principal)2 SpnegoCredential (org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential)2 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)2