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);
}
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();
}
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;
}
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;
}
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();
}
Aggregations