use of com.nimbusds.jwt.SignedJWT in project tomee by apache.
the class Tokens method asToken.
public static String asToken(final String claims) throws Exception {
final PrivateKey pk = readPrivateKey("/testkey.pem");
try {
final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);
final SignedJWT jwt = new SignedJWT(header, claimsSet);
jwt.sign(new RSASSASigner(pk));
return jwt.serialize();
} catch (Exception e) {
throw new RuntimeException("Could not sign JWT");
}
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRJSONWebTokenUtil method retrieveAuthenticationToken.
/**
* returns the access token from Request Header "Authorization"
* if the token is invalid an MCRRestAPIException is thrown
*
* @param request - the HTTPServletRequest object
* @return the JSON Web Token or null, if not provided in request
* @throws MCRRestAPIException
*/
public static SignedJWT retrieveAuthenticationToken(HttpServletRequest request) throws MCRRestAPIException {
String auth = request.getHeader("Authorization");
if (auth != null && auth.startsWith("Bearer ")) {
String authToken = auth.substring(7).trim();
try {
JWSObject jwsObj = JWSObject.parse(authToken);
SignedJWT signedJWT = jwsObj.getPayload().toSignedJWT();
// JWK class does equals only by object id
if (signedJWT.verify(new RSASSAVerifier((RSAPublicKey) MCRJSONWebTokenUtil.RSA_KEYS.getPublic())) && jwsObj.getHeader().getJWK().toJSONString().equals(JWK.parse(signedJWT.getJWTClaimsSet().getJSONObjectClaim("sub_jwk")).toJSONString())) {
Date expires = signedJWT.getJWTClaimsSet().getExpirationTime();
if (Instant.now().isBefore(expires.toInstant())) {
return signedJWT;
} else {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.GERMANY).withZone(ZoneId.systemDefault());
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The Authentication Token expired at " + formatter.format(expires.toInstant()), "Please log-in again."));
}
} else {
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "The signature of the Authentication Token could not be verified.", null));
}
} catch (ParseException | JOSEException e) {
LOGGER.error(e);
throw new MCRRestAPIException(Status.UNAUTHORIZED, new MCRRestAPIError(MCRRestAPIError.CODE_INVALID_AUTHENCATION, "Authentication is invalid.", e.getMessage()));
}
} else {
return null;
}
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRJSONWebTokenUtil method createEmptyJWTwithPublicKey.
/**
* creates an empty JSON Web Token
*
* @param webAppBaseURL - the base url of the application
*
* @return the JSON WebToken
*/
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {
ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString()).issueTime(Date.from(currentTime.toInstant())).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) {
LOGGER.error(e);
}
return signedJWT;
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method uploadObject.
/**
* uploads a MyCoRe Object
* based upon:
* http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/
*
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param uploadedInputStream - the inputstream from HTTP Post request
* @param fileDetails - the file information from HTTP Post request
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
public static Response uploadObject(UriInfo info, HttpServletRequest request, InputStream uploadedInputStream, FormDataContentDisposition fileDetails) throws MCRRestAPIException {
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
java.nio.file.Path fXML = null;
try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
SAXBuilder sb = new SAXBuilder();
Document docOut = sb.build(uploadedInputStream);
MCRObjectID mcrID = MCRObjectID.getInstance(docOut.getRootElement().getAttributeValue("ID"));
if (mcrID.getNumberAsInteger() == 0) {
mcrID = MCRObjectID.getNextFreeId(mcrID.getBase());
}
fXML = UPLOAD_DIR.resolve(mcrID + ".xml");
docOut.getRootElement().setAttribute("ID", mcrID.toString());
docOut.getRootElement().setAttribute("label", mcrID.toString());
XMLOutputter xmlOut = new XMLOutputter(Format.getPrettyFormat());
try (BufferedWriter bw = Files.newBufferedWriter(fXML, StandardCharsets.UTF_8)) {
xmlOut.output(docOut, bw);
}
MCRSession mcrSession = MCRSessionMgr.getCurrentSession();
MCRUserInformation currentUser = mcrSession.getUserInformation();
MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
mcrSession.setUserInformation(apiUser);
// handles "create" as well
MCRObjectCommands.updateFromFile(fXML.toString(), false);
mcrSession.setUserInformation(currentUser);
return Response.created(info.getBaseUriBuilder().path("v1/objects/" + mcrID).build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
} catch (Exception e) {
LOGGER.error("Unable to Upload file: {}", String.valueOf(fXML), e);
throw new MCRRestAPIException(Status.BAD_REQUEST, new MCRRestAPIError(MCRRestAPIError.CODE_WRONG_PARAMETER, "Unable to Upload file: " + String.valueOf(fXML), e.getMessage()));
} finally {
if (fXML != null) {
try {
Files.delete(fXML);
} catch (IOException e) {
LOGGER.error("Unable to delete temporary workflow file: {}", String.valueOf(fXML), e);
}
}
}
}
use of com.nimbusds.jwt.SignedJWT in project mycore by MyCoRe-Org.
the class MCRRestAPIUploadHelper method uploadDerivate.
/**
* creates or updates a MyCoRe derivate
* @param info - the Jersey UriInfo object
* @param request - the HTTPServletRequest object
* @param mcrObjID - the MyCoRe Object ID
* @param label - the label of the new derivate
* @param overwriteOnExistingLabel, if true an existing MyCoRe derivate with the given label will be returned
* @return a Jersey Response object
* @throws MCRRestAPIException
*/
public static Response uploadDerivate(UriInfo info, HttpServletRequest request, String mcrObjID, String label, boolean overwriteOnExistingLabel) throws MCRRestAPIException {
Response response = Response.status(Status.INTERNAL_SERVER_ERROR).build();
SignedJWT signedJWT = MCRJSONWebTokenUtil.retrieveAuthenticationToken(request);
// File fXML = null;
MCRObjectID mcrObjIDObj = MCRObjectID.getInstance(mcrObjID);
try (MCRJPATransactionWrapper mtw = new MCRJPATransactionWrapper()) {
MCRSession session = MCRServlet.getSession(request);
MCRUserInformation currentUser = session.getUserInformation();
MCRUserInformation apiUser = MCRUserManager.getUser(MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(signedJWT));
session.setUserInformation(apiUser);
MCRObject mcrObj = MCRMetadataManager.retrieveMCRObject(mcrObjIDObj);
MCRObjectID derID = null;
if (overwriteOnExistingLabel) {
for (MCRMetaLinkID derLink : mcrObj.getStructure().getDerivates()) {
if (label.equals(derLink.getXLinkLabel()) || label.equals(derLink.getXLinkTitle())) {
derID = derLink.getXLinkHrefID();
}
}
}
if (derID == null) {
derID = MCRObjectID.getNextFreeId(mcrObjIDObj.getProjectId() + "_derivate");
MCRDerivate mcrDerivate = new MCRDerivate();
mcrDerivate.setLabel(label);
mcrDerivate.setId(derID);
mcrDerivate.setSchema("datamodel-derivate.xsd");
mcrDerivate.getDerivate().setLinkMeta(new MCRMetaLinkID("linkmeta", mcrObjIDObj, null, null));
mcrDerivate.getDerivate().setInternals(new MCRMetaIFS("internal", UPLOAD_DIR.resolve(derID.toString()).toString()));
MCRMetadataManager.create(mcrDerivate);
MCRMetadataManager.addOrUpdateDerivateToObject(mcrObjIDObj, new MCRMetaLinkID("derobject", derID, null, label));
}
response = Response.created(info.getBaseUriBuilder().path("v1/objects/" + mcrObjID + "/derivates/" + derID).build()).type("application/xml; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, MCRJSONWebTokenUtil.createJWTAuthorizationHeader(signedJWT)).build();
session.setUserInformation(currentUser);
} catch (Exception e) {
LOGGER.error("Exeption while uploading derivate", e);
}
return response;
}
Aggregations