Search in sources :

Example 26 with JWK

use of com.nimbusds.jose.jwk.JWK in project ddf by codice.

the class OAuthPluginTest method setUp.

@Before
public void setUp() throws Exception {
    // Generate the RSA key pair to sign tokens
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
    String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
    validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
    invalidAlgorithm = Algorithm.HMAC256("WRONG");
    ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
    Resource jwkResource = new Resource(jwk, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(eq(new URL(JWK_ENDPOINT)))).thenReturn(jwkResource);
    String content = IOUtils.toString(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream("metadata.json")), StandardCharsets.UTF_8);
    Resource metadataResource = new Resource(content, APPLICATION_JSON);
    when(resourceRetriever.retrieveResource(eq(new URL(METADATA_ENDPOINT)))).thenReturn(metadataResource);
    tokenStorage = mock(TokenStorage.class);
    oauthPlugin = new OAuthPluginWithMockWebClient(tokenStorage);
    oauthPlugin.setResourceRetriever(resourceRetriever);
}
Also used : KeyPair(java.security.KeyPair) RSAPublicKey(java.security.interfaces.RSAPublicKey) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) Resource(com.nimbusds.jose.util.Resource) KeyPairGenerator(java.security.KeyPairGenerator) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) TokenStorage(org.codice.ddf.security.token.storage.api.TokenStorage) URL(java.net.URL) DISCOVERY_URL(org.codice.ddf.security.token.storage.api.TokenStorage.DISCOVERY_URL) JWK(com.nimbusds.jose.jwk.JWK) Before(org.junit.Before)

Example 27 with JWK

use of com.nimbusds.jose.jwk.JWK in project iaf by ibissource.

the class ApiListenerServletTest method createJWT.

private String createJWT() throws Exception {
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).build();
    JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
    builder.issuer("JWTPipeTest");
    builder.subject("UnitTest");
    builder.audience("Framework");
    builder.jwtID("1234");
    SignedJWT signedJWT = new SignedJWT(jwsHeader, builder.build());
    KeyStore keystore = PkiUtil.createKeyStore(TestFileUtils.getTestFileURL("/JWT/jwt_keystore.p12"), "geheim", KeystoreType.PKCS12, "Keys for signing");
    KeyManager[] keymanagers = PkiUtil.createKeyManagers(keystore, "geheim", null);
    X509KeyManager keyManager = (X509KeyManager) keymanagers[0];
    PrivateKey privateKey = keyManager.getPrivateKey("1");
    PublicKey publicKey = keystore.getCertificate("1").getPublicKey();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyOperations(Collections.singleton(KeyOperation.SIGN)).algorithm(JWSAlgorithm.RS256).keyStore(keystore).build();
    DefaultJWSSignerFactory factory = new DefaultJWSSignerFactory();
    JWSSigner jwsSigner = factory.createJWSSigner(jwk, JWSAlgorithm.RS256);
    signedJWT.sign(jwsSigner);
    return signedJWT.serialize();
}
Also used : PrivateKey(java.security.PrivateKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) URIBuilder(org.apache.http.client.utils.URIBuilder) MultipartEntityBuilder(nl.nn.adapterframework.http.mime.MultipartEntityBuilder) SignedJWT(com.nimbusds.jwt.SignedJWT) KeyStore(java.security.KeyStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) DefaultJWSSignerFactory(com.nimbusds.jose.crypto.factories.DefaultJWSSignerFactory) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader) JWK(com.nimbusds.jose.jwk.JWK)

Example 28 with JWK

use of com.nimbusds.jose.jwk.JWK 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 oldJWT - the given JSON Web Token
 *
 * @return the new JSON WebToken
 */
private static SignedJWT createJWT(SignedJWT oldJWT) {
    if (oldJWT == null) {
        return null;
    }
    String submittedUser = MCRJSONWebTokenUtil.retrieveUsernameFromAuthenticationToken(oldJWT);
    JWK clientPubKey = MCRJSONWebTokenUtil.retrievePublicKeyFromAuthenticationToken(oldJWT);
    if (submittedUser != null && clientPubKey != null) {
        return MCRJSONWebTokenUtil.createJWT(submittedUser, Collections.singletonList("restapi"), MCRFrontendUtil.getBaseURL(), clientPubKey);
    }
    return null;
}
Also used : JWK(com.nimbusds.jose.jwk.JWK)

Example 29 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 30 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)44 Test (org.junit.jupiter.api.Test)18 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)17 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)17 StandardCharsets (java.nio.charset.StandardCharsets)16 Function (java.util.function.Function)16 SecretKeySpec (javax.crypto.spec.SecretKeySpec)16 MockResponse (okhttp3.mockwebserver.MockResponse)16 MockWebServer (okhttp3.mockwebserver.MockWebServer)16 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)16 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)16 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)16 AfterEach (org.junit.jupiter.api.AfterEach)16 BeforeEach (org.junit.jupiter.api.BeforeEach)16 HttpHeaders (org.springframework.http.HttpHeaders)16 MediaType (org.springframework.http.MediaType)16 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)16 ClientAuthenticationMethod (org.springframework.security.oauth2.core.ClientAuthenticationMethod)16 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)16