Search in sources :

Example 86 with ResponseEntity

use of org.springframework.http.ResponseEntity 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
 */
@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) {
    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.StandardScopes.OPENID.getScope())) {
            throw new Exception("Registration request scopes do not contain " + OidcConstants.StandardScopes.OPENID.getScope());
        }
        final OidcRegisteredService registeredService = new OidcRegisteredService();
        registeredService.setName(registrationRequest.getClientName());
        registeredService.setSectorIdentifierUri(registrationRequest.getSectorIdentifierUri());
        registeredService.setSubjectType(registrationRequest.getSubjectType());
        if (StringUtils.equalsIgnoreCase(OidcSubjectTypes.PAIRWISE.getType(), registeredService.getSubjectType())) {
            registeredService.setUsernameAttributeProvider(new PairwiseOidcRegisteredServiceUsernameAttributeProvider());
        }
        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) PairwiseOidcRegisteredServiceUsernameAttributeProvider(org.apereo.cas.services.PairwiseOidcRegisteredServiceUsernameAttributeProvider) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 87 with ResponseEntity

use of org.springframework.http.ResponseEntity in project cas by apereo.

the class OidcIntrospectionEndpointController method createIntrospectionResponse.

private ResponseEntity<OidcIntrospectionAccessTokenResponse> createIntrospectionResponse(final OAuthRegisteredService service, final AccessToken ticket) {
    final OidcIntrospectionAccessTokenResponse introspect = new OidcIntrospectionAccessTokenResponse();
    introspect.setActive(true);
    introspect.setClientId(service.getClientId());
    final Authentication authentication = ticket.getAuthentication();
    final String subject = authentication.getPrincipal().getId();
    introspect.setSub(subject);
    introspect.setUniqueSecurityName(subject);
    introspect.setExp(ticket.getExpirationPolicy().getTimeToLive());
    introspect.setIat(ticket.getCreationTime().toInstant().toEpochMilli());
    final Object methods = authentication.getAttributes().get(AuthenticationManager.AUTHENTICATION_METHOD_ATTRIBUTE);
    final String realmNames = CollectionUtils.toCollection(methods).stream().map(Object::toString).collect(Collectors.joining(","));
    introspect.setRealmName(realmNames);
    introspect.setTokenType(OAuth20Constants.TOKEN_TYPE_BEARER);
    final String grant = authentication.getAttributes().getOrDefault(OAuth20Constants.GRANT_TYPE, StringUtils.EMPTY).toString().toLowerCase();
    introspect.setGrantType(grant);
    introspect.setScope(OidcConstants.StandardScopes.OPENID.getScope());
    introspect.setAud(service.getServiceId());
    introspect.setIss(casProperties.getAuthn().getOidc().getIssuer());
    return new ResponseEntity<>(introspect, HttpStatus.OK);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) Authentication(org.apereo.cas.authentication.Authentication) OidcIntrospectionAccessTokenResponse(org.apereo.cas.oidc.introspection.OidcIntrospectionAccessTokenResponse)

Example 88 with ResponseEntity

use of org.springframework.http.ResponseEntity in project cas by apereo.

the class OidcRevocationEndpointController method handleRequestInternal.

/**
 * Handle request for revocation.
 *
 * @param request  the request
 * @param response the response
 * @return the jwk set
 */
@GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.REVOCATION_URL)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) {
    try {
        final CredentialsExtractor<UsernamePasswordCredentials> authExtractor = new BasicAuthExtractor();
        final UsernamePasswordCredentials credentials = authExtractor.extract(Pac4jUtils.getPac4jJ2EContext(request, response));
        if (credentials == null) {
            throw new IllegalArgumentException("No credentials are provided to verify introspection on the access token");
        }
        final OAuthRegisteredService service = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, credentials.getUsername());
        if (this.validator.checkServiceValid(service) && this.validator.checkParameterExist(request, OAuth20Constants.ACCESS_TOKEN) && this.validator.checkClientSecret(service, credentials.getPassword())) {
            final String token = request.getParameter(OidcConstants.TOKEN);
            if (StringUtils.isNotBlank(token)) {
                this.ticketRegistry.deleteTicket(token);
            }
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return new ResponseEntity<>(HttpStatus.OK);
}
Also used : BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) ResponseEntity(org.springframework.http.ResponseEntity) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 89 with ResponseEntity

use of org.springframework.http.ResponseEntity in project alf.io by alfio-event.

the class ReservationApiController method validateEUVat.

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/vat-validation", method = RequestMethod.POST)
@Transactional
public ResponseEntity<VatDetail> validateEUVat(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, PaymentForm paymentForm, Locale locale, HttpServletRequest request) {
    String country = paymentForm.getVatCountryCode();
    Optional<Triple<Event, TicketReservation, VatDetail>> vatDetail = eventRepository.findOptionalByShortName(eventName).flatMap(e -> ticketReservationRepository.findOptionalReservationById(reservationId).map(r -> Pair.of(e, r))).filter(e -> EnumSet.of(INCLUDED, NOT_INCLUDED).contains(e.getKey().getVatStatus())).filter(e -> vatChecker.isVatCheckingEnabledFor(e.getKey().getOrganizationId())).flatMap(e -> vatChecker.checkVat(paymentForm.getVatNr(), country, e.getKey().getOrganizationId()).map(vd -> Triple.of(e.getLeft(), e.getRight(), vd)));
    vatDetail.filter(t -> t.getRight().isValid()).ifPresent(t -> {
        VatDetail vd = t.getRight();
        String billingAddress = vd.getName() + "\n" + vd.getAddress();
        PriceContainer.VatStatus vatStatus = determineVatStatus(t.getLeft().getVatStatus(), t.getRight().isVatExempt());
        ticketReservationRepository.updateBillingData(vatStatus, vd.getVatNr(), country, paymentForm.isInvoiceRequested(), reservationId);
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, t.getLeft(), Locale.forLanguageTag(t.getMiddle().getUserLanguage()));
        ticketReservationRepository.addReservationInvoiceOrReceiptModel(reservationId, Json.toJson(orderSummary));
        ticketReservationRepository.updateTicketReservation(reservationId, t.getMiddle().getStatus().name(), paymentForm.getEmail(), paymentForm.getFullName(), paymentForm.getFirstName(), paymentForm.getLastName(), locale.getLanguage(), billingAddress, null, Optional.ofNullable(paymentForm.getPaymentMethod()).map(PaymentProxy::name).orElse(null));
        paymentForm.getTickets().forEach((ticketId, owner) -> {
            if (isNotEmpty(owner.getEmail()) && ((isNotEmpty(owner.getFirstName()) && isNotEmpty(owner.getLastName())) || isNotEmpty(owner.getFullName()))) {
                ticketHelper.preAssignTicket(eventName, reservationId, ticketId, owner, Optional.empty(), request, (tr) -> {
                }, Optional.empty());
            }
        });
    });
    return vatDetail.map(Triple::getRight).map(vd -> {
        if (vd.isValid()) {
            return ResponseEntity.ok(vd);
        } else {
            return new ResponseEntity<VatDetail>(HttpStatus.BAD_REQUEST);
        }
    }).orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
Also used : Triple(org.apache.commons.lang3.tuple.Triple) ValidationResult(alfio.model.result.ValidationResult) java.util(java.util) TicketHelper(alfio.controller.api.support.TicketHelper) PaymentProxy(alfio.model.transaction.PaymentProxy) TicketReservationRepository(alfio.repository.TicketReservationRepository) PaymentForm(alfio.controller.form.PaymentForm) BindingResult(org.springframework.validation.BindingResult) StringUtils.isNotEmpty(org.apache.commons.lang3.StringUtils.isNotEmpty) RequestContextUtils(org.springframework.web.servlet.support.RequestContextUtils) Json(alfio.util.Json) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) Pair(org.apache.commons.lang3.tuple.Pair) EuVatChecker(alfio.manager.EuVatChecker) UserDetails(org.springframework.security.core.userdetails.UserDetails) Triple(org.apache.commons.lang3.tuple.Triple) VatStatus(alfio.model.PriceContainer.VatStatus) TemplateManager(alfio.util.TemplateManager) UpdateTicketOwnerForm(alfio.controller.form.UpdateTicketOwnerForm) EventRepository(alfio.repository.EventRepository) Collectors(java.util.stream.Collectors) HttpStatus(org.springframework.http.HttpStatus) TicketReservationManager(alfio.manager.TicketReservationManager) alfio.model(alfio.model) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) ResponseEntity(org.springframework.http.ResponseEntity) I18nManager(alfio.manager.i18n.I18nManager) AllArgsConstructor(lombok.AllArgsConstructor) Authentication(org.springframework.security.core.Authentication) Transactional(org.springframework.transaction.annotation.Transactional) PaymentProxy(alfio.model.transaction.PaymentProxy) VatStatus(alfio.model.PriceContainer.VatStatus) Transactional(org.springframework.transaction.annotation.Transactional)

Example 90 with ResponseEntity

use of org.springframework.http.ResponseEntity in project Saturn by vipshop.

the class DashboardRefreshRestApiController method dashboardRefresh.

/**
 * 根据ZK集群key,刷新该集群的dashboard信息
 *
 * @param zkClusterKey
 * @param request
 * @return
 * @throws SaturnJobConsoleException
 */
@RequestMapping(value = "/dashboard/refresh", method = { RequestMethod.POST, RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> dashboardRefresh(String zkClusterKey, HttpServletRequest request) throws SaturnJobConsoleException {
    try {
        checkMissingParameter("zkClusterKey", zkClusterKey);
        long beforeRefresh = System.currentTimeMillis();
        dashboardService.refreshStatistics2DB(zkClusterKey);
        long afterRefresh = System.currentTimeMillis();
        long takeTime = afterRefresh - beforeRefresh;
        return new ResponseEntity<Object>(takeTime, HttpStatus.OK);
    } catch (SaturnJobConsoleException e) {
        throw e;
    } catch (Exception e) {
        throw new SaturnJobConsoleHttpException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage(), e);
    }
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) SaturnJobConsoleException(com.vip.saturn.job.console.exception.SaturnJobConsoleException) SaturnJobConsoleHttpException(com.vip.saturn.job.console.exception.SaturnJobConsoleHttpException) SaturnJobConsoleException(com.vip.saturn.job.console.exception.SaturnJobConsoleException) SaturnJobConsoleHttpException(com.vip.saturn.job.console.exception.SaturnJobConsoleHttpException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

ResponseEntity (org.springframework.http.ResponseEntity)1188 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)419 HttpHeaders (org.springframework.http.HttpHeaders)398 Test (org.junit.Test)120 ApiOperation (io.swagger.annotations.ApiOperation)116 RestAccessControl (org.entando.entando.web.common.annotation.RestAccessControl)108 HashMap (java.util.HashMap)104 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)103 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)98 HttpStatus (org.springframework.http.HttpStatus)88 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)85 ArrayList (java.util.ArrayList)80 GetMapping (org.springframework.web.bind.annotation.GetMapping)79 Timed (com.codahale.metrics.annotation.Timed)68 IOException (java.io.IOException)67 List (java.util.List)65 URI (java.net.URI)49 MediaType (org.springframework.http.MediaType)48 Test (org.junit.jupiter.api.Test)46 HttpEntity (org.springframework.http.HttpEntity)46