Search in sources :

Example 1 with PostMapping

use of org.springframework.web.bind.annotation.PostMapping in project cas by apereo.

the class ConfigurationStateController method updateConfiguration.

/**
     * Update configuration map.
     *
     * @param jsonInput the json input
     * @param request   the request
     * @param response  the response
     */
@PostMapping("/updateConfiguration")
@ResponseBody
public void updateConfiguration(@RequestBody final Map<String, Map<String, String>> jsonInput, final HttpServletRequest request, final HttpServletResponse response) {
    ensureEndpointAccessIsAuthorized(request, response);
    if (isUpdateEnabled()) {
        final Map<String, String> newData = jsonInput.get("new");
        configurationPropertiesEnvironmentManager.savePropertyForStandaloneProfile(Pair.of(newData.get("key"), newData.get("value")));
        eventPublisher.publishEvent(new CasConfigurationModifiedEvent(this, !casProperties.getEvents().isTrackConfigurationModifications()));
    }
}
Also used : CasConfigurationModifiedEvent(org.apereo.cas.support.events.config.CasConfigurationModifiedEvent) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 2 with PostMapping

use of org.springframework.web.bind.annotation.PostMapping 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
     * @throws Exception the exception
     */
@PostMapping(value = "/resolveattrs")
@ResponseBody
public Map<String, Object> resolvePrincipalAttributes(@RequestParam final String uid, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    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 3 with PostMapping

use of org.springframework.web.bind.annotation.PostMapping in project cas by apereo.

the class OidcDynamicClientRegistrationEndpointController method handleRequestInternal.

/**
     * Handle request.
     *
     * @param jsonInput the json input
     * @param request   the request
     * @param response  the response
     * @return the model and view
     * @throws Exception the exception
     */
@PostMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.REGISTRATION_URL, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<OidcClientRegistrationResponse> handleRequestInternal(@RequestBody final String jsonInput, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    try {
        final OidcClientRegistrationRequest registrationRequest = this.clientRegistrationRequestSerializer.from(jsonInput);
        LOGGER.debug("Received client registration request [{}]", registrationRequest);
        if (registrationRequest.getScopes().isEmpty()) {
            throw new Exception("Registration request does not contain any scope values");
        }
        if (!registrationRequest.getScope().contains(OidcConstants.OPENID)) {
            throw new Exception("Registration request scopes do not contain [{}]" + OidcConstants.OPENID);
        }
        final OidcRegisteredService registeredService = new OidcRegisteredService();
        registeredService.setName(registrationRequest.getClientName());
        if (StringUtils.isNotBlank(registrationRequest.getJwksUri())) {
            registeredService.setJwks(registrationRequest.getJwksUri());
            registeredService.setSignIdToken(true);
        }
        final String uri = registrationRequest.getRedirectUris().stream().findFirst().get();
        registeredService.setServiceId(uri);
        registeredService.setClientId(clientIdGenerator.getNewString());
        registeredService.setClientSecret(clientSecretGenerator.getNewString());
        registeredService.setEvaluationOrder(Integer.MIN_VALUE);
        final Set<String> supportedScopes = new HashSet<>(casProperties.getAuthn().getOidc().getScopes());
        supportedScopes.retainAll(registrationRequest.getScopes());
        final OidcClientRegistrationResponse clientResponse = getClientRegistrationResponse(registrationRequest, registeredService);
        registeredService.setScopes(supportedScopes);
        final Set<String> processedScopes = new LinkedHashSet<>(supportedScopes);
        registeredService.setScopes(processedScopes);
        registeredService.setDescription("Dynamically registered service ".concat(registeredService.getName()).concat(" with grant types ").concat(clientResponse.getGrantTypes().stream().collect(Collectors.joining(","))).concat(" and with scopes ").concat(registeredService.getScopes().stream().collect(Collectors.joining(","))).concat(" and response types ").concat(clientResponse.getResponseTypes().stream().collect(Collectors.joining(","))));
        registeredService.setDynamicallyRegistered(true);
        scopeToAttributesFilter.reconcile(registeredService);
        return new ResponseEntity<>(clientResponse, HttpStatus.CREATED);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        final Map<String, String> map = new HashMap<>();
        map.put("error", "invalid_client_metadata");
        map.put("error_message", e.getMessage());
        return new ResponseEntity(map, HttpStatus.BAD_REQUEST);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) OidcClientRegistrationRequest(org.apereo.cas.oidc.dynareg.OidcClientRegistrationRequest) HashMap(java.util.HashMap) Map(java.util.Map) OidcClientRegistrationResponse(org.apereo.cas.oidc.dynareg.OidcClientRegistrationResponse) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with PostMapping

use of org.springframework.web.bind.annotation.PostMapping in project cas by apereo.

the class RegisteredServiceResource method createService.

/**
     * Create new service.
     *
     * @param tgtId             ticket granting ticket id URI path param
     * @param serviceDataHolder the service to register and save in rest form
     * @return {@link ResponseEntity} representing RESTful response
     */
@PostMapping(value = "/v1/services/add/{tgtId:.+}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createService(@ModelAttribute final ServiceDataHolder serviceDataHolder, @PathVariable("tgtId") final String tgtId) {
    try {
        if (StringUtils.isBlank(this.attributeName) || StringUtils.isBlank(this.attributeValue)) {
            throw new IllegalArgumentException("Attribute name and/or value must be configured");
        }
        final TicketGrantingTicket ticket = this.centralAuthenticationService.getTicket(tgtId, TicketGrantingTicket.class);
        if (ticket == null || ticket.isExpired()) {
            throw new InvalidTicketException("Ticket-granting ticket " + tgtId + " is not found");
        }
        final Map<String, Object> attributes = ticket.getAuthentication().getPrincipal().getAttributes();
        if (attributes.containsKey(this.attributeName)) {
            final Collection<String> attributeValuesToCompare = new HashSet<>();
            final Object value = attributes.get(this.attributeName);
            if (value instanceof Collection) {
                attributeValuesToCompare.addAll((Collection<String>) value);
            } else {
                attributeValuesToCompare.add(value.toString());
            }
            if (attributeValuesToCompare.contains(this.attributeValue)) {
                final RegisteredService service = serviceDataHolder.getRegisteredService();
                final RegisteredService savedService = this.servicesManager.save(service);
                return new ResponseEntity<>(String.valueOf(savedService.getId()), HttpStatus.OK);
            }
        }
        throw new IllegalArgumentException("Request is not authorized");
    } catch (final InvalidTicketException e) {
        return new ResponseEntity<>("TicketGrantingTicket could not be found", HttpStatus.NOT_FOUND);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : RegexRegisteredService(org.apereo.cas.services.RegexRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) ResponseEntity(org.springframework.http.ResponseEntity) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Collection(java.util.Collection) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 5 with PostMapping

use of org.springframework.web.bind.annotation.PostMapping in project cas by apereo.

the class TicketsResource method createTicketGrantingTicket.

/**
     * Create new ticket granting ticket.
     *
     * @param requestBody username and password application/x-www-form-urlencoded values
     * @param request     raw HttpServletRequest used to call this method
     * @return ResponseEntity representing RESTful response
     * @throws JsonProcessingException in case of JSON parsing failure
     */
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) throws JsonProcessingException {
    try {
        final Credential credential = this.credentialFactory.fromRequestBody(requestBody);
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, credential);
        final TicketGrantingTicket tgtId = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
        final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);
        final String tgtUrl = ticketReference.toString();
        final String response = new StringBuilder(SUCCESSFUL_TGT_CREATED_INITIAL_LENGTH + tgtUrl.length()).append(DOCTYPE_AND_OPENING_FORM).append(tgtUrl).append(REST_OF_THE_FORM_AND_CLOSING_TAGS).toString();
        return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
    } catch (final AuthenticationException e) {
        final List<String> authnExceptions = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.toList());
        final Map<String, List<String>> errorsMap = new HashMap<>();
        errorsMap.put("authentication_exceptions", authnExceptions);
        LOGGER.error("[{}] Caused by: [{}]", e.getMessage(), authnExceptions, e);
        try {
            return new ResponseEntity<>(this.jacksonPrettyWriter.writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
        } catch (final JsonProcessingException exception) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (final BadRequestException e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) ResponseEntity(org.springframework.http.ResponseEntity) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

PostMapping (org.springframework.web.bind.annotation.PostMapping)40 Profile (com.erudika.scoold.core.Profile)20 Post (com.erudika.scoold.core.Post)9 HashMap (java.util.HashMap)6 Report (com.erudika.scoold.core.Report)4 Map (java.util.Map)4 RegisteredService (org.apereo.cas.services.RegisteredService)4 ResponseEntity (org.springframework.http.ResponseEntity)4 Translation (com.erudika.para.core.Translation)3 Reply (com.erudika.scoold.core.Reply)3 RegexRegisteredService (org.apereo.cas.services.RegexRegisteredService)3 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)3 Comment (com.erudika.scoold.core.Comment)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Date (java.util.Date)2 HashSet (java.util.HashSet)2 LinkedHashMap (java.util.LinkedHashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 Locale (java.util.Locale)2 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)2