Search in sources :

Example 6 with JWK

use of com.nimbusds.jose.jwk.JWK in project mycore by MyCoRe-Org.

the class MCRJSONWebTokenUtil method retrievePublicKeyFromLoginToken.

/**
 * retrieves the client public key from Login Token
 *
 * @param token - the serialized JSON Web Token from login
 * @return the public key as JWK object
 */
public static JWK retrievePublicKeyFromLoginToken(String token) {
    JWK result = null;
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(token);
        // Decrypt with shared key
        jweObject.decrypt(new RSADecrypter(RSA_KEYS.getPrivate()));
        // Extract payload
        SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
        result = signedJWT.getHeader().getJWK();
        RSAKey publicKey = RSAKey.parse(result.toJSONObject());
        if (signedJWT.verify(new RSASSAVerifier(publicKey))) {
            return result;
        }
    } catch (ParseException | JOSEException e) {
        LOGGER.error(e);
    }
    return null;
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) JWEObject(com.nimbusds.jose.JWEObject) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) JWK(com.nimbusds.jose.jwk.JWK) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 7 with JWK

use of com.nimbusds.jose.jwk.JWK in project mycore by MyCoRe-Org.

the class MCRRestAPIAuthentication method authorize.

/**
 * Validation: https://jwt.io/ Public Key: http://localhost:8080/api/v1/auth/public_key.txt
 *
 * Unauthenticated requests should return a response whose header contains a HTTP 401 Unauthorized status and a
 * WWW-Authenticate field.
 *
 * 200 OK Content-Type: application/json;charset=UTF-8
 *
 * { "access_token": "NgCXRK...MzYjw", "token_type": "Bearer", "expires_at": 1372700873, "refresh_token":
 * "NgAagA...Um_SHo" }
 *
 * Returning the JWT (Java Web Token to the client is not properly specified). We use the "Authorization" Header in
 * the response, which is unusual but not strictly forbidden.
 *
 * @param authorization - content HTTP Header Authorization
 * @return response message as JSON
 */
@POST
@Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" })
@Path("/login")
public Response authorize(@DefaultValue("") @HeaderParam("Authorization") String authorization) {
    String username = null;
    String password = null;
    JWK clientPubKey = null;
    String userPwd = null;
    if (authorization.startsWith("Basic ")) {
        byte[] encodedAuth = authorization.substring(6).trim().getBytes(StandardCharsets.ISO_8859_1);
        userPwd = new String(Base64.getDecoder().decode(encodedAuth), StandardCharsets.ISO_8859_1);
    }
    if (authorization.startsWith(HEADER_PREFIX_BEARER)) {
        userPwd = MCRJSONWebTokenUtil.retrieveUsernamePasswordFromLoginToken(authorization.substring(7).trim());
        clientPubKey = MCRJSONWebTokenUtil.retrievePublicKeyFromLoginToken(authorization.substring(7).trim());
    }
    if (userPwd != null && userPwd.contains(":")) {
        int splitPos = userPwd.indexOf(":");
        username = userPwd.substring(0, splitPos);
        password = userPwd.substring(splitPos + 1);
    }
    // validate username and password
    if (username != null && password != null && MCRUserManager.checkPassword(username, password) != null) {
        SignedJWT jwt = MCRJSONWebTokenUtil.createJWT(username, Collections.singletonList("restapi"), MCRFrontendUtil.getBaseURL(), clientPubKey);
        if (jwt != null) {
            String msg = "{" + "\n    \"login_successful\":true," + "\n    \"access_token\": \"" + jwt.serialize() + "\"," + "\n    \"token_type\": \"Bearer\"" + "\n}";
            return Response.ok(msg).type("application/json; charset=UTF-8").header(HEADER_NAME_AUTHORIZATION, HEADER_PREFIX_BEARER + jwt.serialize()).build();
        }
    }
    String msg = "{" + "\n    \"login_successful\":false," + "\n    \"error\": \"login_failed\"" + "\n    \"error_description\": " + "\"Login failed. Please provider proper user name and password via HTTP Basic Authentication.\"" + "\n}";
    return Response.status(Status.FORBIDDEN).header("WWW-Authenticate", "Basic realm=\"MyCoRe REST API\"").entity(msg).type("application/json; charset=UTF-8").build();
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) JWK(com.nimbusds.jose.jwk.JWK) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Aggregations

JWK (com.nimbusds.jose.jwk.JWK)7 JOSEException (com.nimbusds.jose.JOSEException)4 SignedJWT (com.nimbusds.jwt.SignedJWT)4 JWSHeader (com.nimbusds.jose.JWSHeader)2 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)2 RSASSAVerifier (com.nimbusds.jose.crypto.RSASSAVerifier)2 RSAKey (com.nimbusds.jose.jwk.RSAKey)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 ParseException (java.text.ParseException)2 ZonedDateTime (java.time.ZonedDateTime)2 JWEObject (com.nimbusds.jose.JWEObject)1 RSADecrypter (com.nimbusds.jose.crypto.RSADecrypter)1 JWKSet (com.nimbusds.jose.jwk.JWKSet)1 URL (java.net.URL)1 POST (javax.ws.rs.POST)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1