Search in sources :

Example 81 with Authentication

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

the class SingleSignOnSessionsReportController method getActiveSsoSessions.

/**
 * Gets sso sessions.
 *
 * @param option the option
 * @return the sso sessions
 */
private Collection<Map<String, Object>> getActiveSsoSessions(final SsoSessionReportOptions option) {
    final Collection<Map<String, Object>> activeSessions = new ArrayList<>();
    final ISOStandardDateFormat dateFormat = new ISOStandardDateFormat();
    getNonExpiredTicketGrantingTickets().stream().map(TicketGrantingTicket.class::cast).filter(tgt -> !(option == SsoSessionReportOptions.DIRECT && tgt.getProxiedBy() != null)).forEach(tgt -> {
        final Authentication authentication = tgt.getAuthentication();
        final Principal principal = authentication.getPrincipal();
        final Map<String, Object> sso = new HashMap<>(SsoSessionAttributeKeys.values().length);
        sso.put(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.getAttributeKey(), principal.getId());
        sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE.getAttributeKey(), authentication.getAuthenticationDate());
        sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE_FORMATTED.getAttributeKey(), dateFormat.format(DateTimeUtils.dateOf(authentication.getAuthenticationDate())));
        sso.put(SsoSessionAttributeKeys.NUMBER_OF_USES.getAttributeKey(), tgt.getCountOfUses());
        sso.put(SsoSessionAttributeKeys.TICKET_GRANTING_TICKET.getAttributeKey(), tgt.getId());
        sso.put(SsoSessionAttributeKeys.PRINCIPAL_ATTRIBUTES.getAttributeKey(), principal.getAttributes());
        sso.put(SsoSessionAttributeKeys.AUTHENTICATION_ATTRIBUTES.getAttributeKey(), authentication.getAttributes());
        if (option != SsoSessionReportOptions.DIRECT) {
            if (tgt.getProxiedBy() != null) {
                sso.put(SsoSessionAttributeKeys.IS_PROXIED.getAttributeKey(), Boolean.TRUE);
                sso.put(SsoSessionAttributeKeys.PROXIED_BY.getAttributeKey(), tgt.getProxiedBy().getId());
            } else {
                sso.put(SsoSessionAttributeKeys.IS_PROXIED.getAttributeKey(), Boolean.FALSE);
            }
        }
        sso.put(SsoSessionAttributeKeys.AUTHENTICATED_SERVICES.getAttributeKey(), tgt.getServices());
        activeSessions.add(sso);
    });
    return activeSessions;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) RequestParam(org.springframework.web.bind.annotation.RequestParam) Getter(lombok.Getter) BaseCasMvcEndpoint(org.apereo.cas.web.BaseCasMvcEndpoint) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) Beans(org.apereo.cas.configuration.support.Beans) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) ToString(lombok.ToString) GetMapping(org.springframework.web.bind.annotation.GetMapping) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) PostMapping(org.springframework.web.bind.annotation.PostMapping) DateTimeUtils(org.apereo.cas.util.DateTimeUtils) Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) Set(java.util.Set) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) ISOStandardDateFormat(org.apereo.cas.util.ISOStandardDateFormat) ModelAndView(org.springframework.web.servlet.ModelAndView) Slf4j(lombok.extern.slf4j.Slf4j) Principal(org.apereo.cas.authentication.principal.Principal) WebAsyncTask(org.springframework.web.context.request.async.WebAsyncTask) Ticket(org.apereo.cas.ticket.Ticket) HashMap(java.util.HashMap) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) Authentication(org.apereo.cas.authentication.Authentication) ArrayList(java.util.ArrayList) ToString(lombok.ToString) HashMap(java.util.HashMap) Map(java.util.Map) Principal(org.apereo.cas.authentication.principal.Principal) ISOStandardDateFormat(org.apereo.cas.util.ISOStandardDateFormat)

Example 82 with Authentication

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

the class YubiKeyAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException {
    final YubiKeyCredential yubiKeyCredential = (YubiKeyCredential) credential;
    final String otp = yubiKeyCredential.getToken();
    if (!YubicoClient.isValidOTPFormat(otp)) {
        LOGGER.debug("Invalid OTP format [{}]", otp);
        throw new AccountNotFoundException("OTP format is invalid");
    }
    final Authentication authentication = WebUtils.getInProgressAuthentication();
    if (authentication == null) {
        throw new IllegalArgumentException("CAS has no reference to an authentication event to locate a principal");
    }
    final Principal principal = authentication.getPrincipal();
    final String uid = principal.getId();
    final String publicId = registry.getAccountValidator().getTokenPublicId(otp);
    if (!this.registry.isYubiKeyRegisteredFor(uid, publicId)) {
        LOGGER.debug("YubiKey public id [{}] is not registered for user [{}]", publicId, uid);
        throw new AccountNotFoundException("YubiKey id is not recognized in registry");
    }
    try {
        final VerificationResponse response = this.client.verify(otp);
        final ResponseStatus status = response.getStatus();
        if (status.compareTo(ResponseStatus.OK) == 0) {
            LOGGER.debug("YubiKey response status [{}] at [{}]", status, response.getTimestamp());
            return createHandlerResult(yubiKeyCredential, this.principalFactory.createPrincipal(uid));
        }
        throw new FailedLoginException("Authentication failed with status: " + status);
    } catch (final YubicoVerificationException | YubicoValidationFailure e) {
        LOGGER.error(e.getMessage(), e);
        throw new FailedLoginException("YubiKey validation failed: " + e.getMessage());
    }
}
Also used : VerificationResponse(com.yubico.client.v2.VerificationResponse) FailedLoginException(javax.security.auth.login.FailedLoginException) ResponseStatus(com.yubico.client.v2.ResponseStatus) Authentication(org.apereo.cas.authentication.Authentication) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) YubicoValidationFailure(com.yubico.client.v2.exceptions.YubicoValidationFailure) Principal(org.apereo.cas.authentication.principal.Principal) YubicoVerificationException(com.yubico.client.v2.exceptions.YubicoVerificationException)

Example 83 with Authentication

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

the class CookieRetrievingCookieGenerator method isRememberMeAuthentication.

private boolean isRememberMeAuthentication(final RequestContext requestContext) {
    final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
    final String value = request.getParameter(RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME);
    LOGGER.debug("Locating request parameter [{}] with value [{}]", RememberMeCredential.REQUEST_PARAMETER_REMEMBER_ME, value);
    boolean isRememberMe = StringUtils.isNotBlank(value) && WebUtils.isRememberMeAuthenticationEnabled(requestContext);
    if (!isRememberMe) {
        LOGGER.debug("Request does not indicate a remember-me authentication event. Locating authentication object from the request context...");
        final Authentication auth = WebUtils.getAuthentication(requestContext);
        if (auth != null) {
            final Map<String, Object> attributes = auth.getAttributes();
            LOGGER.debug("Located authentication attributes [{}]", attributes);
            if (attributes.containsKey(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME)) {
                final Object rememberMeValue = attributes.getOrDefault(RememberMeCredential.AUTHENTICATION_ATTRIBUTE_REMEMBER_ME, false);
                LOGGER.debug("Located remember-me authentication attribute [{}]", rememberMeValue);
                isRememberMe = CollectionUtils.wrapSet(rememberMeValue).contains(true);
            }
        }
    }
    LOGGER.debug("Is this request from a remember-me authentication event? [{}]", BooleanUtils.toStringYesNo(isRememberMe));
    return isRememberMe;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication)

Example 84 with Authentication

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

the class TicketValidationResourceResolver method resolveFrom.

@Override
public String[] resolveFrom(final JoinPoint joinPoint, final Object object) {
    final List<String> auditResourceResults = new ArrayList<>();
    final String ticketId = AopUtils.unWrapJoinPoint(joinPoint).getArgs()[0].toString();
    auditResourceResults.add(ticketId);
    if (object instanceof Assertion) {
        final Assertion assertion = Assertion.class.cast(object);
        final Authentication authn = assertion.getPrimaryAuthentication();
        try (StringWriter writer = new StringWriter()) {
            final ObjectWriter objectWriter = mapper.writer();
            final Map<String, Object> results = new LinkedHashMap<>();
            results.put("principal", authn.getPrincipal().getId());
            final Map<String, Object> attributes = new LinkedHashMap<>(authn.getAttributes());
            attributes.putAll(authn.getPrincipal().getAttributes());
            results.put("attributes", attributes);
            objectWriter.writeValue(writer, results);
            auditResourceResults.add(writer.toString());
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return auditResourceResults.toArray(new String[] {});
}
Also used : StringWriter(java.io.StringWriter) Authentication(org.apereo.cas.authentication.Authentication) ArrayList(java.util.ArrayList) Assertion(org.apereo.cas.validation.Assertion) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) LinkedHashMap(java.util.LinkedHashMap)

Example 85 with Authentication

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

the class UniquePrincipalAuthenticationPolicy method isSatisfiedBy.

@Override
public boolean isSatisfiedBy(final Authentication authentication) throws Exception {
    try {
        final Principal authPrincipal = authentication.getPrincipal();
        final long count = this.ticketRegistry.getTickets(t -> {
            boolean pass = TicketGrantingTicket.class.isInstance(t) && !t.isExpired();
            if (pass) {
                final Principal principal = TicketGrantingTicket.class.cast(t).getAuthentication().getPrincipal();
                pass = principal.getId().equalsIgnoreCase(authPrincipal.getId());
            }
            return pass;
        }).count();
        if (count == 0) {
            LOGGER.debug("Authentication policy is satisfied with [{}]", authPrincipal.getId());
            return true;
        }
        LOGGER.warn("Authentication policy cannot be satisfied for principal [{}] because [{}] sessions currently exist", authPrincipal.getId(), count);
        return false;
    } catch (final Exception e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : AuthenticationPolicy(org.apereo.cas.authentication.AuthenticationPolicy) Slf4j(lombok.extern.slf4j.Slf4j) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) GeneralSecurityException(java.security.GeneralSecurityException) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal) AllArgsConstructor(lombok.AllArgsConstructor) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) GeneralSecurityException(java.security.GeneralSecurityException) Principal(org.apereo.cas.authentication.principal.Principal) GeneralSecurityException(java.security.GeneralSecurityException)

Aggregations

Authentication (org.apereo.cas.authentication.Authentication)144 RegisteredService (org.apereo.cas.services.RegisteredService)61 Test (org.junit.Test)48 Service (org.apereo.cas.authentication.principal.Service)44 Principal (org.apereo.cas.authentication.principal.Principal)38 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)24 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)21 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)21 Event (org.springframework.webflow.execution.Event)20 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)18 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)18 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)15 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)15 HashMap (java.util.HashMap)14 Assertion (org.apereo.cas.validation.Assertion)14 NeverExpiresExpirationPolicy (org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy)13 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)12 Collection (java.util.Collection)11 AuditableExecutionResult (org.apereo.cas.audit.AuditableExecutionResult)11