use of com.nimbusds.jose.jwk.JWK in project ddf by codice.
the class OAuthSecurityImplTest 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);
oauthSecurity = new OAuthSecurityWithMockWebclient(tokenStorage);
oauthSecurity.setResourceRetriever(resourceRetriever);
}
use of com.nimbusds.jose.jwk.JWK in project flow by vaadin.
the class JwtSecurityContextRepository method encodeJwt.
private String encodeJwt(Authentication authentication) throws JOSEException {
if (authentication == null || trustResolver.isAnonymous(authentication)) {
return null;
}
final Date now = new Date();
final List<String> roles = authentication.getAuthorities().stream().map(Objects::toString).filter(a -> a.startsWith(ROLE_AUTHORITY_PREFIX)).map(a -> a.substring(ROLE_AUTHORITY_PREFIX.length())).collect(Collectors.toList());
SignedJWT signedJWT;
JWSHeader jwsHeader = new JWSHeader(jwsAlgorithm);
JWKSelector jwkSelector = new JWKSelector(JWKMatcher.forJWSHeader(jwsHeader));
List<JWK> jwks = jwkSource.get(jwkSelector, null);
JWK jwk = jwks.get(0);
JWSSigner signer = new DefaultJWSSignerFactory().createJWSSigner(jwk, jwsAlgorithm);
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(authentication.getName()).issuer(issuer).issueTime(now).expirationTime(new Date(now.getTime() + expiresIn * 1000)).claim(ROLES_CLAIM, roles).build();
signedJWT = new SignedJWT(jwsHeader, claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
use of com.nimbusds.jose.jwk.JWK in project knox by apache.
the class JWKSResourceTest method testE2E.
/**
* End to End test that verifies the token acquired from JWKS endpoint.
*/
@Test
public void testE2E() throws Exception {
/* get a signed JWT token */
final JWT testToken = getTestToken("RS256");
final JWKSResource jwksResource = new JWKSResource();
jwksResource.context = context;
jwksResource.request = request;
jwksResource.init();
/* get JWKS keyset */
final Response retResponse = jwksResource.getJwksResponse();
/* following lines just verifies the token */
final JWKSet jwks = JWKSet.parse(retResponse.getEntity().toString());
Assert.assertTrue("No keys found", jwks.getKeys().size() > 0);
final JWK jwk = jwks.getKeys().get(0);
Assert.assertNotNull("No private key found", jwk.toRSAKey().toPublicKey());
final PublicKey pk = jwk.toRSAKey().toPublicKey();
final JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) pk);
Assert.assertTrue("Cannot verify the token, wrong certificate", testToken.verify(verifier));
}
use of com.nimbusds.jose.jwk.JWK in project ddf by codice.
the class TestOidc method beforeTest.
@BeforeExam
public void beforeTest() {
try {
getServiceManager().waitForAllBundles();
getServiceManager().waitForHttpEndpoint(WHO_AM_I_URL.getUrl());
getServiceManager().waitForHttpEndpoint(SERVICE_ROOT + "/catalog/query");
oldPolicyManagerProps = getSecurityPolicy().configureWebContextPolicy(OIDC_AUTH_TYPES, OIDC_AUTH_TYPES, null, null);
// start stub server
server = new StubServer(Integer.parseInt(IDP_PORT.getPort())).run();
server.start();
// Generate the RSA key pair
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair keyPair = gen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// Convert to JSON Web Key (JWK) format
JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
invalidAlgorithm = Algorithm.HMAC256("WRONG");
setUp();
// Configure OIDC Handler
handlerConfig = new Hashtable<>();
handlerConfig.put("idpType", "Keycloak");
handlerConfig.put("clientId", DDF_CLIENT_ID);
handlerConfig.put("realm", "master");
handlerConfig.put(SECRET, DDF_CLIENT_SECRET);
handlerConfig.put("logoutUri", URL_START.toString() + LOGOUT_URL_PATH);
handlerConfig.put("baseUri", URL_START.toString() + "/auth");
handlerConfig.put("discoveryUri", URL_START.toString() + METADATA_PATH);
handlerConfig.put(SCOPE, DDF_SCOPE);
handlerConfig.put("useNonce", true);
handlerConfig.put("responseMode", FORM_POST);
setConfig();
} catch (Exception e) {
LoggingUtils.failWithThrowableStacktrace(e, "Failed in @BeforeExam: ");
}
}
use of com.nimbusds.jose.jwk.JWK in project ddf by codice.
the class OidcRealmTest method setup.
@Before
public void setup() throws Exception {
realm = new OidcRealm();
// Generate the RSA key pair
KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
gen.initialize(2048);
KeyPair keyPair = gen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
validAlgorithm = Algorithm.RSA256(publicKey, privateKey);
invalidAlgorithm = Algorithm.HMAC256("WRONG");
JWK sigJwk = new RSAKey.Builder(publicKey).privateKey(privateKey).keyUse(KeyUse.SIGNATURE).keyID(UUID.randomUUID().toString()).build();
String jwk = "{\"keys\": [" + sigJwk.toPublicJWK().toJSONString() + "] }";
OIDCProviderMetadata oidcProviderMetadata = mock(OIDCProviderMetadata.class);
when(oidcProviderMetadata.getIDTokenJWSAlgs()).thenReturn(ImmutableList.of(JWSAlgorithm.RS256));
when(oidcProviderMetadata.getIssuer()).thenReturn(new Issuer("http://localhost:8080/auth/realms/master"));
when(oidcProviderMetadata.getJWKSetURI()).thenReturn(new URI("http://localhost:8080/auth/realms/master/protocol/openid-connect/certs"));
ResourceRetriever resourceRetriever = mock(ResourceRetriever.class);
Resource resource = new Resource(jwk, APPLICATION_JSON);
when(resourceRetriever.retrieveResource(any())).thenReturn(resource);
OidcConfiguration configuration = mock(OidcConfiguration.class);
when(configuration.getClientId()).thenReturn("ddf-client");
when(configuration.getSecret()).thenReturn("secret");
when(configuration.isUseNonce()).thenReturn(true);
when(configuration.getResponseType()).thenReturn("code");
when(configuration.findProviderMetadata()).thenReturn(oidcProviderMetadata);
when(configuration.findResourceRetriever()).thenReturn(resourceRetriever);
OidcHandlerConfiguration handlerConfiguration = mock(OidcHandlerConfiguration.class);
when(handlerConfiguration.getOidcConfiguration()).thenReturn(configuration);
when(handlerConfiguration.getOidcClient(any())).thenReturn(mock(OidcClient.class));
realm.setOidcHandlerConfiguration(handlerConfiguration);
realm.setUsernameAttributeList(Collections.singletonList("preferred_username"));
JWT jwt = mock(JWT.class);
AccessToken accessToken = new BearerAccessToken(getAccessTokenBuilder().sign(validAlgorithm));
AuthorizationCode authorizationCode = new AuthorizationCode();
WebContext webContext = getWebContext();
oidcCredentials = mock(OidcCredentials.class);
when(oidcCredentials.getIdToken()).thenReturn(jwt);
when(oidcCredentials.getIdToken()).thenReturn(jwt);
when(oidcCredentials.getAccessToken()).thenReturn(accessToken);
when(oidcCredentials.getCode()).thenReturn(authorizationCode);
authenticationToken = mock(OidcAuthenticationToken.class);
when(authenticationToken.getCredentials()).thenReturn(oidcCredentials);
when(authenticationToken.getContext()).thenReturn(webContext);
}
Aggregations