use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method deleteAllFiles.
/**
* deletes all files inside a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - the MyCoRe Object ID
* @param pathParamMcrDerID - the MyCoRe Derivate ID
* @return a Jersey Response Object
* @throws MCRRestAPIException
*/
public static Response deleteAllFiles(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID) throws MCRRestAPIException {
Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
SortedMap<String, String> parameter = new TreeMap<>();
parameter.put("mcrObjectID", pathParamMcrObjID);
parameter.put("mcrDerivateID", pathParamMcrDerID);
String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
if (base64Signature == null) {
// ToDo error handling
}
if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
// MCRSession session = MCRServlet.getSession(request);
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation currentUser = session.getUserInformation();
MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
session.setUserInformation(apiUser);
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
// MCRAccessManager.checkPermission uses CACHE, which seems to be dirty from other calls
MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
final MCRPath rootPath = MCRPath.getPath(der.getId().toString(), "/");
try {
Files.walkFileTree(rootPath, MCRRecursiveDeleter.instance());
Files.createDirectory(rootPath);
} catch (IOException e) {
LOGGER.error(e);
}
}
session.setUserInformation(currentUser);
response = Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
}
} else {
throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "Delete failed.", "The submitted data could not be validated."));
}
return response;
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method uploadFile.
/**
* uploads a file into a given derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param pathParamMcrObjID - a MyCoRe Object ID
* @param pathParamMcrDerID - a MyCoRe Derivate ID
* @param uploadedInputStream - the inputstream from HTTP Post request
* @param fileDetails - the file information from HTTP Post request
* @param formParamPath - the path of the file inside the derivate
* @param formParamMaindoc - true, if this file should be marked as maindoc
* @param formParamUnzip - true, if the upload is zip file that should be unzipped inside the derivate
* @param formParamMD5 - the MD5 sum of the uploaded file
* @param formParamSize - the size of the uploaded file
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
public static Response uploadFile(UriInfo info, HttpServletRequest request, String pathParamMcrObjID, String pathParamMcrDerID, InputStream uploadedInputStream, FormDataContentDisposition fileDetails, String formParamPath, boolean formParamMaindoc, boolean formParamUnzip, String formParamMD5, Long formParamSize) throws MCRRestAPIException {
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
SortedMap<String, String> parameter = new TreeMap<>();
parameter.put("mcrObjectID", pathParamMcrObjID);
parameter.put("mcrDerivateID", pathParamMcrDerID);
parameter.put("path", formParamPath);
parameter.put("maindoc", Boolean.toString(formParamMaindoc));
parameter.put("unzip", Boolean.toString(formParamUnzip));
parameter.put("md5", formParamMD5);
parameter.put("size", Long.toString(formParamSize));
String base64Signature = request.getHeader("X-MyCoRe-RestAPI-Signature");
if (base64Signature == null) {
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The submitted data could not be validated.", "Please provide a signature as HTTP header 'X-MyCoRe-RestAPI-Signature'."));
}
if (verifyPropertiesWithSignature(parameter, base64Signature, MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(signedJWT))) {
try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
// MCRSession session = MCRServlet.getSession(request);
MCRSession session = MCRSessionMgr.getCurrentSession();
MCRUserInformation currentUser = session.getUserInformation();
MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
session.setUserInformation(apiUser);
MCRObjectID objID = MCRObjectID.getInstance(pathParamMcrObjID);
MCRObjectID derID = MCRObjectID.getInstance(pathParamMcrDerID);
MCRAccessManager.invalidPermissionCache(derID.toString(), PERMISSION_WRITE);
if (MCRAccessManager.checkPermission(derID.toString(), PERMISSION_WRITE)) {
MCRDerivate der = MCRMetadataManager.retrieveMCRDerivate(derID);
java.nio.file.Path derDir = null;
String path = null;
if (der.getOwnerID().equals(objID)) {
try {
derDir = UPLOAD_DIR.resolve(derID.toString());
if (Files.exists(derDir)) {
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
}
path = formParamPath.replace("\\", "/").replace("../", "");
while (path.startsWith("/")) {
path = path.substring(1);
}
MCRDirectory difs = MCRDirectory.getRootDirectory(derID.toString());
if (difs == null) {
difs = new MCRDirectory(derID.toString());
}
der.getDerivate().getInternals().setIFSID(difs.getID());
der.getDerivate().getInternals().setSourcePath(derDir.toString());
if (formParamUnzip) {
String maindoc = null;
try (ZipInputStream zis = new ZipInputStream(new BufferedInputStream(uploadedInputStream))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
LOGGER.debug("Unzipping: {}", entry.getName());
java.nio.file.Path target = derDir.resolve(entry.getName());
Files.createDirectories(target.getParent());
Files.copy(zis, target, StandardCopyOption.REPLACE_EXISTING);
if (maindoc == null && !entry.isDirectory()) {
maindoc = entry.getName();
}
}
} catch (IOException e) {
LOGGER.error(e);
}
MCRFileImportExport.importFiles(derDir.toFile(), difs);
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(maindoc);
}
} else {
java.nio.file.Path saveFile = derDir.resolve(path);
Files.createDirectories(saveFile.getParent());
Files.copy(uploadedInputStream, saveFile, StandardCopyOption.REPLACE_EXISTING);
// delete old file
MCRFileImportExport.importFiles(derDir.toFile(), difs);
if (formParamMaindoc) {
der.getDerivate().getInternals().setMainDoc(path);
}
}
MCRMetadataManager.update(der);
Files.walkFileTree(derDir, MCRRecursiveDeleter.instance());
} catch (IOException | MCRPersistenceException | MCRAccessException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Status.INTERNAL_SERVER_ERROR, new MCRRestAPIError(MCRRestAPIError.CODE_INTERNAL_ERROR, "Internal error", e.getMessage()));
}
}
session.setUserInformation(currentUser);
return Response.created(info.getBaseUriBuilder().path("v1/objects/" + objID + "/derivates/" + derID + "/contents").build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
}
}
}
throw new MCRRestAPIException(Status.FORBIDDEN, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_DATA, "File upload failed.", "The submitted data could not be validated."));
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRJSONWebTokenUtil method createJWT.
/**
* creates a JSON Web Token with user id, roles and client public key
*
* @param user - the user that should be returned
* @param roles - the roles that should be returned
* @param webAppBaseURL - the base url of the application
* @param clientPublicKey - the client public key as JSON Web Key
*
* @return the JSON WebToken
*/
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).issueTime(Date.from(currentTime.toInstant())).notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user).claim("roles", roles).claim("sub_jwk", clientPublicKey).build();
String keyID = UUID.randomUUID().toString();
JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
try {
signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
} catch (JOSEException e) {
// TODO Auto-generated catch block
LOGGER.error(e);
}
System.out.println("JWT: " + signedJWT.serialize());
return signedJWT;
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRRestAPIAuthentication method initAuthorization.
/**
* @return the server public key as Java Web Token
*/
@GET
@Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" })
public Response initAuthorization() {
SignedJWT jwt = MCRJSONWebTokenUtil.createEmptyJWTwithPublicKey("http:/localhost:8080");
String msg = "{" + "\n \"access_token\": \"" + jwt + "\"," + "\n}";
return Response.ok(msg).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, HEADER_PREFIX_BEARER + jwt.serialize()).build();
}
use of com.nimbusds.jwt.SignedJWT in project gravitee-management-rest-api by gravitee-io.
the class ReferenceSerializer method serialize.
public String serialize(IdentityReference reference) throws Exception {
// Create HMAC signer
JWSSigner signer = new MACSigner(secretKey.getEncoded());
// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(reference.getReference()).issuer(reference.getSource()).build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
// Apply the HMAC protection
signedJWT.sign(signer);
// Create JWE object with signed JWT as payload
JWEObject jweObject = new JWEObject(new JWEHeader.Builder(JWEAlgorithm.DIR, EncryptionMethod.A256GCM).contentType(// required to signal nested JWT
"JWT").build(), new Payload(signedJWT));
// Perform encryption
jweObject.encrypt(new DirectEncrypter(secretKey.getEncoded()));
// Serialize to compact form
return new String(Base64.getEncoder().encode(jweObject.serialize().getBytes()));
}
Aggregations