Search in sources :

Example 11 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class OAuth20AccessTokenControllerTests method internalVerifyClientOK.

private void internalVerifyClientOK(final RegisteredService service, final boolean basicAuth, final boolean refreshToken, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final OAuthCode code = addCode(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
    if (basicAuth) {
        final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
        final String value = Base64.encodeBase64String(auth.getBytes(StandardCharsets.UTF_8));
        mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
    } else {
        mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
        mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    }
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertNull(oAuth20AccessTokenController.getTicketRegistry().getTicket(code.getId()));
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    if (json) {
        assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
        }
        assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
        assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + "=AT-"));
        if (refreshToken) {
            assertTrue(body.contains(OAuthConstants.REFRESH_TOKEN + "=RT-"));
        }
        assertTrue(body.contains(OAuthConstants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + '=', "&");
    }
    final AccessToken accessToken = oAuth20AccessTokenController.getTicketRegistry().getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());
    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 12 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class PersonDirectoryAttributeResolutionController method resolvePrincipalAttributes.

/**
 * Resolve principal attributes map.
 *
 * @param uid      the uid
 * @param request  the request
 * @param response the response
 * @return the map
 */
@PostMapping(value = "/resolveattrs")
@ResponseBody
public Map<String, Object> resolvePrincipalAttributes(@RequestParam final String uid, final HttpServletRequest request, final HttpServletResponse response) {
    ensureEndpointAccessIsAuthorized(request, response);
    final Principal p = personDirectoryPrincipalResolver.resolve(new BasicIdentifiableCredential(uid));
    final Map<String, Object> map = new LinkedHashMap<>();
    map.put("uid", p.getId());
    map.put("attributes", p.getAttributes());
    return map;
}
Also used : BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) Principal(org.apereo.cas.authentication.principal.Principal) LinkedHashMap(java.util.LinkedHashMap) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 13 with Principal

use of org.apereo.cas.authentication.principal.Principal 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 Principal

use of org.apereo.cas.authentication.principal.Principal 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 Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class DefaultAuthenticationResultBuilder method buildAuthenticationHistory.

private static void buildAuthenticationHistory(final Set<Authentication> authentications, final Map<String, Object> authenticationAttributes, final Map<String, Object> principalAttributes, final AuthenticationBuilder authenticationBuilder) {
    LOGGER.debug("Collecting authentication history based on [{}] authentication events", authentications.size());
    authentications.stream().forEach(authn -> {
        final Principal authenticatedPrincipal = authn.getPrincipal();
        LOGGER.debug("Evaluating authentication principal [{}] for inclusion in result", authenticatedPrincipal);
        principalAttributes.putAll(authenticatedPrincipal.getAttributes());
        LOGGER.debug("Collected principal attributes [{}] for inclusion in this result for principal [{}]", principalAttributes, authenticatedPrincipal.getId());
        authn.getAttributes().keySet().stream().forEach(attrName -> {
            if (authenticationAttributes.containsKey(attrName)) {
                LOGGER.debug("Collecting multi-valued authentication attribute [{}]", attrName);
                final Object oldValue = authenticationAttributes.remove(attrName);
                LOGGER.debug("Converting authentication attribute [{}] to a collection of values", attrName);
                final Collection<Object> listOfValues = CollectionUtils.toCollection(oldValue);
                final Object newValue = authn.getAttributes().get(attrName);
                listOfValues.addAll(CollectionUtils.toCollection(newValue));
                authenticationAttributes.put(attrName, listOfValues);
                LOGGER.debug("Collected multi-valued authentication attribute [{}] -> [{}]", attrName, listOfValues);
            } else {
                final Object value = authn.getAttributes().get(attrName);
                if (value != null) {
                    authenticationAttributes.put(attrName, value);
                    LOGGER.debug("Collected single authentication attribute [{}] -> [{}]", attrName, value);
                } else {
                    LOGGER.warn("Authentication attribute [{}] has no value and is not collected", attrName);
                }
            }
        });
        LOGGER.debug("Finalized authentication attributes [{}] for inclusion in this authentication result", authenticationAttributes);
        authenticationBuilder.addSuccesses(authn.getSuccesses()).addFailures(authn.getFailures()).addCredentials(authn.getCredentials());
    });
}
Also used : Principal(org.apereo.cas.authentication.principal.Principal)

Aggregations

Principal (org.apereo.cas.authentication.principal.Principal)114 HashMap (java.util.HashMap)33 RegisteredService (org.apereo.cas.services.RegisteredService)31 Test (org.junit.Test)29 Authentication (org.apereo.cas.authentication.Authentication)26 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)26 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)26 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)25 Map (java.util.Map)23 Slf4j (lombok.extern.slf4j.Slf4j)23 lombok.val (lombok.val)19 List (java.util.List)15 StringUtils (org.apache.commons.lang3.StringUtils)15 OAuthCode (org.apereo.cas.ticket.code.OAuthCode)15 CollectionUtils (org.apereo.cas.util.CollectionUtils)15 ArrayList (java.util.ArrayList)14 Optional (java.util.Optional)14 Service (org.apereo.cas.authentication.principal.Service)14 Collection (java.util.Collection)11 Collectors (java.util.stream.Collectors)10