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);
}
}
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);
}
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);
}
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));
}
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);
}
}
Aggregations