use of org.springframework.web.bind.annotation.RequestBody in project alien4cloud by alien4cloud.
the class AbstractLocationResourcesSecurityController method updateAuthorizedEnvironmentsAndEnvTypePerApplication.
/**
* Update applications,environments and environment types authorized to access the location resource.
*/
@ApiOperation(value = "Update applications,environments and environment types authorized to access the location resource", notes = "Only user with ADMIN role can update authorized applications,environments and environment types for the location.")
@RequestMapping(value = "/environmentsPerApplication", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN')")
public synchronized RestResponse<Void> updateAuthorizedEnvironmentsAndEnvTypePerApplication(@PathVariable String orchestratorId, @PathVariable String locationId, @PathVariable String resourceId, @RequestBody ApplicationEnvironmentAuthorizationUpdateRequest request) {
Location location = locationService.getLocation(orchestratorId, locationId);
locationSecurityService.grantAuthorizationOnLocationIfNecessary(request.getApplicationsToAdd(), request.getEnvironmentsToAdd(), request.getEnvironmentTypesToAdd(), location);
AbstractLocationResourceTemplate resourceTemplate = locationResourceService.getOrFail(resourceId);
if (ArrayUtils.isNotEmpty(request.getApplicationsToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToDelete());
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentsToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, request.getEnvironmentsToDelete());
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToDelete())) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, request.getEnvironmentTypesToDelete());
}
Set<String> envIds = Sets.newHashSet();
if (ArrayUtils.isNotEmpty(request.getApplicationsToAdd())) {
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.APPLICATION, request.getApplicationsToAdd());
// when an app is added, all eventual existing env authorizations are removed
for (String applicationToAddId : request.getApplicationsToAdd()) {
ApplicationEnvironment[] aes = applicationEnvironmentService.getByApplicationId(applicationToAddId);
for (ApplicationEnvironment ae : aes) {
envIds.add(ae.getId());
}
}
if (!envIds.isEmpty()) {
resourcePermissionService.revokePermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envIds.toArray(new String[envIds.size()]));
}
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentsToAdd())) {
List<String> envToAddSet = Arrays.stream(request.getEnvironmentsToAdd()).filter(env -> !envIds.contains(env)).collect(Collectors.toList());
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT, envToAddSet.toArray(new String[envToAddSet.size()]));
}
if (ArrayUtils.isNotEmpty(request.getEnvironmentTypesToAdd())) {
resourcePermissionService.grantPermission(resourceTemplate, (resource -> locationResourceService.saveResource(location, (AbstractLocationResourceTemplate) resource)), Subject.ENVIRONMENT_TYPE, request.getEnvironmentTypesToAdd());
}
return RestResponseBuilder.<Void>builder().build();
}
use of org.springframework.web.bind.annotation.RequestBody 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, "/**/" + OidcConstants.REGISTRATION_URL }, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity handleRequestInternal(@RequestBody final String jsonInput, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
val webContext = new JEEContext(request, response);
if (!getConfigurationContext().getOidcRequestSupport().isValidIssuerForEndpoint(webContext, OidcConstants.REGISTRATION_URL)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
try {
val registrationRequest = (OidcClientRegistrationRequest) getConfigurationContext().getClientRegistrationRequestSerializer().from(jsonInput);
LOGGER.debug("Received client registration request [{}]", registrationRequest);
val containsFragment = registrationRequest.getRedirectUris().stream().anyMatch(uri -> uri.contains("#"));
if (containsFragment) {
throw new IllegalArgumentException("Redirect URI cannot contain a fragment");
}
val servicesManager = getConfigurationContext().getServicesManager();
val registeredService = registrationRequest.getRedirectUris().stream().map(uri -> (OidcRegisteredService) OAuth20Utils.getRegisteredOAuthServiceByRedirectUri(servicesManager, uri)).filter(Objects::nonNull).findFirst().orElseGet(OidcRegisteredService::new);
if (StringUtils.isNotBlank(registrationRequest.getClientName())) {
registeredService.setName(registrationRequest.getClientName());
} else if (StringUtils.isBlank(registeredService.getName())) {
registeredService.setName(RandomUtils.randomAlphabetic(GENERATED_CLIENT_NAME_LENGTH));
}
val serviceId = String.join("|", registrationRequest.getRedirectUris());
registeredService.setServiceId(serviceId);
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());
} else {
val jwks = registrationRequest.getJwks();
if (jwks != null && !jwks.getJsonWebKeys().isEmpty()) {
jwks.getJsonWebKeys().stream().filter(key -> StringUtils.isBlank(key.getKeyId())).forEach(key -> key.setKeyId(RandomUtils.randomAlphabetic(6)));
registeredService.setJwks(jwks.toJson());
}
}
if (StringUtils.isNotBlank(registrationRequest.getTokenEndpointAuthMethod())) {
registeredService.setTokenEndpointAuthenticationMethod(registrationRequest.getTokenEndpointAuthMethod());
}
registeredService.setClientId(getConfigurationContext().getClientIdGenerator().getNewString());
registeredService.setClientSecret(getConfigurationContext().getClientSecretGenerator().getNewString());
registeredService.setEvaluationOrder(0);
val urls = org.springframework.util.StringUtils.collectionToCommaDelimitedString(registrationRequest.getPostLogoutRedirectUris());
registeredService.setLogoutUrl(urls);
if (StringUtils.isNotBlank(registrationRequest.getLogo())) {
registeredService.setLogo(registrationRequest.getLogo());
}
if (StringUtils.isNotBlank(registrationRequest.getPolicyUri())) {
registeredService.setInformationUrl(registrationRequest.getPolicyUri());
}
if (StringUtils.isNotBlank(registrationRequest.getTermsOfUseUri())) {
registeredService.setPrivacyUrl(registrationRequest.getTermsOfUseUri());
}
if (!StringUtils.equalsIgnoreCase("none", registrationRequest.getUserInfoSignedReponseAlg())) {
registeredService.setUserInfoSigningAlg(registrationRequest.getUserInfoSignedReponseAlg());
}
registeredService.setUserInfoEncryptedResponseAlg(registrationRequest.getUserInfoEncryptedResponseAlg());
if (StringUtils.isNotBlank(registeredService.getUserInfoEncryptedResponseAlg())) {
if (StringUtils.isBlank(registrationRequest.getUserInfoEncryptedResponseEncoding())) {
registeredService.setUserInfoEncryptedResponseEncoding(OidcUserProfileSigningAndEncryptionService.USER_INFO_RESPONSE_ENCRYPTION_ENCODING_DEFAULT);
} else {
registeredService.setUserInfoEncryptedResponseEncoding(registrationRequest.getUserInfoEncryptedResponseEncoding());
}
}
val properties = getConfigurationContext().getCasProperties();
val supportedScopes = new HashSet<>(properties.getAuthn().getOidc().getDiscovery().getScopes());
val prefix = properties.getServer().getPrefix();
val clientResponse = OidcClientRegistrationUtils.getClientRegistrationResponse(registeredService, prefix);
clientResponse.setClientSecretExpiresAt(0);
val accessToken = generateRegistrationAccessToken(request, response, registeredService, registrationRequest);
val encodedAccessToken = OAuth20JwtAccessTokenEncoder.builder().accessToken(accessToken).registeredService(registeredService).service(accessToken.getService()).accessTokenJwtBuilder(getConfigurationContext().getAccessTokenJwtBuilder()).casProperties(getConfigurationContext().getCasProperties()).build().encode();
clientResponse.setRegistrationAccessToken(encodedAccessToken);
registeredService.setScopes(supportedScopes);
val processedScopes = new LinkedHashSet<>(supportedScopes);
registeredService.setScopes(processedScopes);
if (!registrationRequest.getDefaultAcrValues().isEmpty()) {
val multifactorPolicy = new DefaultRegisteredServiceMultifactorPolicy();
multifactorPolicy.setMultifactorAuthenticationProviders(new HashSet<>(registrationRequest.getDefaultAcrValues()));
registeredService.setMultifactorPolicy(multifactorPolicy);
}
if (StringUtils.isNotBlank(registrationRequest.getIdTokenSignedResponseAlg())) {
registeredService.setIdTokenSigningAlg(registrationRequest.getIdTokenSignedResponseAlg());
registeredService.setSignIdToken(true);
}
if (StringUtils.isNotBlank(registrationRequest.getIdTokenEncryptedResponseAlg())) {
registeredService.setIdTokenEncryptionAlg(registrationRequest.getIdTokenEncryptedResponseAlg());
registeredService.setEncryptIdToken(true);
}
if (StringUtils.isNotBlank(registrationRequest.getIdTokenEncryptedResponseEncoding())) {
registeredService.setIdTokenEncryptionEncoding(registrationRequest.getIdTokenEncryptedResponseEncoding());
registeredService.setEncryptIdToken(true);
}
registrationRequest.getContacts().forEach(c -> {
val contact = new DefaultRegisteredServiceContact();
if (c.contains("@")) {
contact.setEmail(c);
contact.setName(c.substring(0, c.indexOf('@')));
} else {
contact.setName(c);
}
registeredService.getContacts().add(contact);
});
registeredService.setDescription("Registered service ".concat(registeredService.getName()));
registeredService.setDynamicallyRegistered(true);
validate(registrationRequest, registeredService);
getConfigurationContext().getServicesManager().save(registeredService);
return new ResponseEntity<>(clientResponse, HttpStatus.CREATED);
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
val map = new HashMap<String, String>();
map.put("error", "invalid_client_metadata");
map.put("error_description", StringUtils.defaultString(e.getMessage(), "None"));
return new ResponseEntity<>(map, HttpStatus.BAD_REQUEST);
}
}
use of org.springframework.web.bind.annotation.RequestBody in project cas by apereo.
the class UmaUpdatePolicyForResourceSetEndpointController method updatePoliciesForResourceSet.
/**
* Update policy for resource set.
*
* @param resourceId the resource id
* @param policyId the policy id
* @param body the body
* @param request the request
* @param response the response
* @return the policy for resource set
*/
@PutMapping(value = '/' + OAuth20Constants.BASE_OAUTH20_URL + "/{resourceId}/" + OAuth20Constants.UMA_POLICY_URL + "/{policyId}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity updatePoliciesForResourceSet(@PathVariable(value = "resourceId") final long resourceId, @PathVariable(value = "policyId") final long policyId, @RequestBody final String body, final HttpServletRequest request, final HttpServletResponse response) {
try {
val profileResult = getAuthenticatedProfile(request, response, OAuth20Constants.UMA_PROTECTION_SCOPE);
val resourceSetResult = getUmaConfigurationContext().getUmaResourceSetRepository().getById(resourceId);
if (resourceSetResult.isEmpty()) {
val model = buildResponseEntityErrorModel(HttpStatus.NOT_FOUND, "Requested resource-set cannot be found");
return new ResponseEntity(model, model, HttpStatus.BAD_REQUEST);
}
val resourceSet = resourceSetResult.get();
resourceSet.validate(profileResult);
val umaRequest = MAPPER.readValue(JsonValue.readHjson(body).toString(), ResourceSetPolicy.class);
val policyResult = resourceSet.getPolicies().stream().filter(p -> p.getId() == policyId).findFirst();
if (policyResult.isPresent()) {
val policy = policyResult.get();
policy.setPermissions(umaRequest.getPermissions());
val currentPolicies = resourceSet.getPolicies().stream().filter(p -> p.getId() != policyId).collect(Collectors.toSet());
currentPolicies.add(policy);
resourceSet.setPolicies(new HashSet<>(currentPolicies));
getUmaConfigurationContext().getUmaResourceSetRepository().save(resourceSet);
val model = CollectionUtils.wrap("entity", resourceSet, "code", HttpStatus.FOUND);
return new ResponseEntity(model, HttpStatus.OK);
}
val model = CollectionUtils.wrap("code", HttpStatus.NOT_FOUND);
return new ResponseEntity(model, HttpStatus.OK);
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
}
return new ResponseEntity("Unable to locate resource-set.", HttpStatus.BAD_REQUEST);
}
use of org.springframework.web.bind.annotation.RequestBody in project proxyee-down by monkeyWie.
the class HttpDownController method bdyUnzip.
@RequestMapping("/bdyUnzip")
public ResultInfo bdyUnzip(@RequestParam String id, @RequestParam boolean ignore, @RequestBody UnzipForm unzipForm) throws IOException {
ResultInfo resultInfo = new ResultInfo();
File file = new File(unzipForm.getFilePath());
if (file.exists() && file.isFile()) {
if (!unzipForm.getFilePath().equalsIgnoreCase(unzipForm.getToPath())) {
if (ignore || BdyZip.isBdyZip(unzipForm.getFilePath())) {
UnzipInfo unzipInfo = new UnzipInfo().setId(id);
if (!FileUtil.exists(unzipForm.getToPath())) {
FileUtil.createDirSmart(unzipForm.getToPath());
}
if (!FileUtil.canWrite(unzipForm.getToPath())) {
resultInfo.setStatus(ResultStatus.BAD.getCode()).setMsg("无权访问解压路径,请修改路径或开放目录写入权限");
return resultInfo;
}
new Thread(() -> {
try {
BdyZip.unzip(unzipForm.getFilePath(), unzipForm.getToPath(), new BdyUnzipCallback() {
@Override
public void onStart() {
unzipInfo.setType(BdyZip.ON_START).setStartTime(System.currentTimeMillis());
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
@Override
public void onFix(long totalSize, long fixSize) {
unzipInfo.setType(BdyZip.ON_FIX).setTotalFixSize(totalSize).setFixSize(fixSize);
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
@Override
public void onFixDone(List<BdyZipEntry> list) {
unzipInfo.setType(BdyZip.ON_FIX_DONE).setTotalFileSize(list.stream().map(entry -> entry.getCompressedSize()).reduce((s1, s2) -> s1 + s2).get());
}
@Override
public void onEntryStart(BdyZipEntry entry) {
unzipInfo.setType(BdyZip.ON_ENTRY_START).setEntry(entry).setCurrFileSize(entry.getCompressedSize()).setCurrWriteSize(0);
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
@Override
public void onEntryWrite(long totalSize, long writeSize) {
unzipInfo.setType(BdyZip.ON_ENTRY_WRITE).setCurrWriteSize(unzipInfo.getCurrWriteSize() + writeSize).setTotalWriteSize(unzipInfo.getTotalWriteSize() + writeSize);
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
@Override
public void onDone() {
unzipInfo.setType(BdyZip.ON_DONE).setEndTime(System.currentTimeMillis());
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
@Override
public void onError(Exception e) {
unzipInfo.setType(BdyZip.ON_ERROR).setErrorMsg(e.toString());
ContentManager.WS.sendMsg(new WsForm(WsDataType.UNZIP_ING, unzipInfo));
}
});
} catch (Exception e) {
LOGGER.error("unzip error:", e);
}
}).start();
} else {
resultInfo.setStatus(ResultStatus.BAD.getCode());
resultInfo.setMsg("解压失败,请确认是否为百度云批量下载zip文件");
}
} else {
resultInfo.setStatus(ResultStatus.BAD.getCode());
resultInfo.setMsg("解压失败,文件路径与解压路径相同");
}
} else {
resultInfo.setStatus(ResultStatus.BAD.getCode());
resultInfo.setMsg("解压失败,文件不存在");
}
return resultInfo;
}
use of org.springframework.web.bind.annotation.RequestBody in project spring-framework by spring-projects.
the class RequestBodyMethodArgumentResolver method resolveArgument.
@Override
public Mono<Object> resolveArgument(MethodParameter param, BindingContext bindingContext, ServerWebExchange exchange) {
RequestBody ann = param.getParameterAnnotation(RequestBody.class);
Assert.state(ann != null, "No RequestBody annotation");
return readBody(param, ann.required(), bindingContext, exchange);
}
Aggregations