Search in sources :

Example 11 with Authentication

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

the class Cas30JsonResponseView method createAuthenticationSuccess.

private CasServiceResponseAuthenticationSuccess createAuthenticationSuccess(final Map<String, Object> model) {
    final CasServiceResponseAuthenticationSuccess success = new CasServiceResponseAuthenticationSuccess();
    success.setAttributes(getModelAttributes(model));
    final Principal principal = getPrincipal(model);
    success.setUser(principal.getId());
    success.setProxyGrantingTicket(getProxyGrantingTicketIou(model));
    final Collection<Authentication> chainedAuthentications = getChainedAuthentications(model);
    if (chainedAuthentications != null && !chainedAuthentications.isEmpty()) {
        final List<String> proxies = chainedAuthentications.stream().map(authn -> authn.getPrincipal().getId()).collect(Collectors.toList());
        success.setProxies(proxies);
    }
    return success;
}
Also used : Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ProtocolAttributeEncoder(org.apereo.cas.authentication.ProtocolAttributeEncoder) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) Principal(org.apereo.cas.authentication.principal.Principal) ServicesManager(org.apereo.cas.services.ServicesManager) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal)

Example 12 with Authentication

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

the class OAuthUserAuthenticator method validate.

@Override
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws CredentialsException {
    final UsernamePasswordCredential casCredential = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
    try {
        final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
        final Service service = this.webApplicationServiceFactory.createService(clientId);
        final RegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(this.servicesManager, clientId);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, casCredential);
        final Authentication authentication = authenticationResult.getAuthentication();
        final Principal principal = authentication.getPrincipal();
        final OAuthUserProfile profile = new OAuthUserProfile();
        final String id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
        LOGGER.debug("Created profile id [{}]", id);
        profile.setId(id);
        final Map<String, Object> attributes = registeredService.getAttributeReleasePolicy().getAttributes(principal, registeredService);
        profile.addAttributes(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 : RegisteredService(org.apereo.cas.services.RegisteredService) Authentication(org.apereo.cas.authentication.Authentication) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) CredentialsException(org.pac4j.core.exception.CredentialsException) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) Principal(org.apereo.cas.authentication.principal.Principal) CredentialsException(org.pac4j.core.exception.CredentialsException) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 13 with Authentication

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

the class PersonDirectoryAttributeResolutionController method releasePrincipalAttributes.

/**
 * Release principal attributes map.
 *
 * @param username the username
 * @param password the password
 * @param service  the service
 * @param request  the request
 * @param response the response
 * @return the map
 * @throws Exception the exception
 */
@PostMapping(value = "/releaseattrs")
@ResponseBody
public Map<String, Object> releasePrincipalAttributes(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    ensureEndpointAccessIsAuthorized(request, response);
    final Map<String, Object> resValidation = new HashMap<>();
    final Service selectedService = this.serviceFactory.createService(service);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
    final UsernamePasswordCredential credential = new UsernamePasswordCredential(username, password);
    final AuthenticationResult result = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(selectedService, credential);
    final Authentication authentication = result.getAuthentication();
    final Principal principal = authentication.getPrincipal();
    final Map<String, Object> attributesToRelease = registeredService.getAttributeReleasePolicy().getAttributes(principal, selectedService, registeredService);
    final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService, registeredService);
    final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
    final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
    builder.setPrincipal(modifiedPrincipal);
    final Authentication finalAuthentication = builder.build();
    final Assertion assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(CollectionUtils.wrap(finalAuthentication)).build();
    final Map<String, Object> model = new LinkedHashMap<>();
    model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
    model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, selectedService);
    resValidation.put("registeredService", registeredService);
    String copy = renderViewAndGetResult(this.cas1ServiceSuccessView, model, request, response).getKey().getCopy();
    resValidation.put("cas1Response", StringEscapeUtils.escapeXml11(copy));
    if (casProperties.getView().getCas2().isV3ForwardCompatible()) {
        copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
    } else {
        copy = renderViewAndGetResult(this.cas2ServiceSuccessView, model, request, response).getKey().getCopy();
    }
    resValidation.put("cas2Response", StringEscapeUtils.escapeXml11(copy));
    copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
    resValidation.put("cas3XmlResponse", StringEscapeUtils.escapeXml11(copy));
    copy = renderViewAndGetResult(this.cas3ServiceJsonView, model, request, response).getValue().getStringCopy();
    resValidation.put("cas3JsonResponse", copy);
    response.reset();
    return resValidation;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assertion(org.apereo.cas.validation.Assertion) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) LinkedHashMap(java.util.LinkedHashMap) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) Authentication(org.apereo.cas.authentication.Authentication) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Principal(org.apereo.cas.authentication.principal.Principal) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 14 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 15 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)

Aggregations

Authentication (org.apereo.cas.authentication.Authentication)125 RegisteredService (org.apereo.cas.services.RegisteredService)58 Service (org.apereo.cas.authentication.principal.Service)44 lombok.val (lombok.val)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)32 Slf4j (lombok.extern.slf4j.Slf4j)32 Principal (org.apereo.cas.authentication.principal.Principal)26 Event (org.springframework.webflow.execution.Event)25 Optional (java.util.Optional)23 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)22 Test (org.junit.Test)21 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)20 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)19 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)17 Collection (java.util.Collection)16 StringUtils (org.apache.commons.lang3.StringUtils)16 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)15 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)15 WebUtils (org.apereo.cas.web.support.WebUtils)14 RequestContext (org.springframework.webflow.execution.RequestContext)14