Search in sources :

Example 86 with SignedJWT

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");
    }
}
Also used : JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 87 with SignedJWT

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;
    }
}
Also used : MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JWSObject(com.nimbusds.jose.JWSObject) DateTimeFormatter(java.time.format.DateTimeFormatter) JOSEException(com.nimbusds.jose.JOSEException) Date(java.util.Date)

Example 88 with SignedJWT

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;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 89 with 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);
            }
        }
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) SAXBuilder(org.jdom2.input.SAXBuilder) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRRestAPIError(org.mycore.restapi.v1.errors.MCRRestAPIError) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) Document(org.jdom2.Document) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRAccessException(org.mycore.access.MCRAccessException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) MCRSession(org.mycore.common.MCRSession) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRUserInformation(org.mycore.common.MCRUserInformation)

Example 90 with SignedJWT

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;
}
Also used : Response(javax.ws.rs.core.Response) MCRSession(org.mycore.common.MCRSession) MCRObject(org.mycore.datamodel.metadata.MCRObject) MCRMetaLinkID(org.mycore.datamodel.metadata.MCRMetaLinkID) MCRDerivate(org.mycore.datamodel.metadata.MCRDerivate) SignedJWT(com.nimbusds.jwt.SignedJWT) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRMetaIFS(org.mycore.datamodel.metadata.MCRMetaIFS) MCRUserInformation(org.mycore.common.MCRUserInformation) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRRestAPIException(org.mycore.restapi.v1.errors.MCRRestAPIException) MCRAccessException(org.mycore.access.MCRAccessException) IOException(java.io.IOException)

Aggregations

SignedJWT (com.nimbusds.jwt.SignedJWT)204 Test (org.junit.Test)84 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)75 Date (java.util.Date)66 HttpServletRequest (javax.servlet.http.HttpServletRequest)64 HttpServletResponse (javax.servlet.http.HttpServletResponse)54 JWSHeader (com.nimbusds.jose.JWSHeader)53 Properties (java.util.Properties)49 ServletException (javax.servlet.ServletException)46 ParseException (java.text.ParseException)31 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)28 JOSEException (com.nimbusds.jose.JOSEException)25 JWSSigner (com.nimbusds.jose.JWSSigner)21 Cookie (javax.servlet.http.Cookie)21 ArrayList (java.util.ArrayList)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)14 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)13 Test (org.junit.jupiter.api.Test)12 OAuth2TokenValidator (org.springframework.security.oauth2.core.OAuth2TokenValidator)12 Cache (javax.cache.Cache)11