com.nimbusds.jwt.PlainJWT Java Examples
The following examples show how to use
com.nimbusds.jwt.PlainJWT.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void invalid_client() throws Exception { RSAKey rsaKey = getRSAKey(); JWSSigner signer = new RSASSASigner(rsaKey); JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("alice") .issuer("https://c2id.com") .claim("client_id", "unknown_client") .expirationTime(new Date(new Date().getTime() + 60 * 1000)) .build(); System.out.println(new PlainJWT(claimsSet).serialize()); SignedJWT signedJWT = new SignedJWT( new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(), claimsSet); signedJWT.sign(signer); String jwt = signedJWT.serialize(); System.out.println(jwt); }
Example #2
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testWithFailingDiscovery() { String assertion = new PlainJWT( new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience(AUDIENCE) .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ).serialize(); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(null); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test(); testObserver.assertError(ServerErrorException.class); testObserver.assertNotComplete(); }
Example #3
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testWithWrongAudience() { String assertion = new PlainJWT( new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience("wrongAudience") .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ).serialize(); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE); when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test(); testObserver.assertError(InvalidClientException.class); testObserver.assertNotComplete(); }
Example #4
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testPlainJwt() { String assertion = new PlainJWT( new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience(AUDIENCE) .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ).serialize(); OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class); String basePath="/"; when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE); when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test(); testObserver.assertError(InvalidClientException.class); testObserver.assertNotComplete(); }
Example #5
Source File: KnoxServiceTest.java From nifi with Apache License 2.0 | 6 votes |
@Test(expected = ParseException.class) public void testPlainJwt() throws Exception { final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); final KeyPair pair = keyGen.generateKeyPair(); final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic(); final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("user-1") .expirationTime(expiration) .build(); final PlainJWT plainJWT = new PlainJWT(claimsSet); final KnoxConfiguration configuration = getConfiguration(publicKey); final KnoxService service = new KnoxService(configuration); service.getAuthenticationFromToken(plainJWT.serialize()); }
Example #6
Source File: FirebaseJwtTokenDecoderTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void unsignedTokenTests() { JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() .subject("test-subject") .expirationTime(Date.from(Instant.now().plusSeconds(60))) .build(); PlainJWT plainJWT = new PlainJWT(claimsSet); FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(mock(RestOperations.class), "https://spring.local", mock(OAuth2TokenValidator.class)); assertThatExceptionOfType(JwtException.class) .isThrownBy(() -> decoder.decode(plainJWT.serialize())) .withMessageStartingWith("An error occurred while attempting to decode the Jwt"); }
Example #7
Source File: JWSServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testisValidSignature_PlainJwt() { JWT assertion = new PlainJWT( new JWTClaimsSet.Builder() .issuer("iss") .subject("client") .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS))) .build() ); assertFalse("Should return false due to ClassCastException",jwsService.isValidSignature(assertion, null)); }
Example #8
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testWithMissingClaims() { String assertion = new PlainJWT(new JWTClaimsSet.Builder().build()).serialize(); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,null).test(); testObserver.assertError(InvalidClientException.class); testObserver.assertNotComplete(); }
Example #9
Source File: ClientAssertionServiceTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void testWithExpiredToken() { String assertion = new PlainJWT( new JWTClaimsSet.Builder() .issuer(ISSUER) .subject(CLIENT_ID) .audience(AUDIENCE) .expirationTime(Date.from(Instant.now().minus(1, ChronoUnit.DAYS))) .build() ).serialize(); TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,null).test(); testObserver.assertError(InvalidClientException.class); testObserver.assertNotComplete(); }
Example #10
Source File: JWTAccessTokenBuilder.java From msf4j with Apache License 2.0 | 5 votes |
/** * To build id token from OauthToken request message context * * @param request Token request message context * @return Signed jwt string. * @throws IdentityOAuth2Exception */ protected String buildIDToken(OAuthTokenReqMessageContext request) throws IdentityOAuth2Exception { String issuer = OAuth2Util.getIDTokenIssuer(); long lifetimeInMillis = OAuthServerConfiguration.getInstance(). getApplicationAccessTokenValidityPeriodInSeconds() * 1000; long curTimeInMillis = Calendar.getInstance().getTimeInMillis(); // setting subject String subject = request.getAuthorizedUser().getAuthenticatedSubjectIdentifier(); if (!StringUtils.isNotBlank(subject)) { subject = request.getAuthorizedUser().getUserName(); } // Set claims to jwt token. JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setSubject(subject); jwtClaimsSet.setAudience(Arrays.asList(request.getOauth2AccessTokenReqDTO().getClientId())); jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getOauth2AccessTokenReqDTO().getClientId()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); addUserClaims(jwtClaimsSet, request.getAuthorizedUser()); if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } return signJWT(jwtClaimsSet, request); }
Example #11
Source File: JWTAccessTokenBuilder.java From msf4j with Apache License 2.0 | 5 votes |
/** * Build a signed jwt token from authorization request message context * * @param request Oauth authorization message context * @return Signed jwt string * @throws IdentityOAuth2Exception */ protected String buildIDToken(OAuthAuthzReqMessageContext request) throws IdentityOAuth2Exception { String issuer = OAuth2Util.getIDTokenIssuer(); long lifetimeInMillis = OAuthServerConfiguration.getInstance(). getApplicationAccessTokenValidityPeriodInSeconds() * 1000; long curTimeInMillis = Calendar.getInstance().getTimeInMillis(); // setting subject String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier(); if (!StringUtils.isNotBlank(subject)) { subject = request.getAuthorizationReqDTO().getUser().getUserName(); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setSubject(subject); jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey())); jwtClaimsSet.setClaim(Constants.AUTHORIZATION_PARTY, request.getAuthorizationReqDTO().getConsumerKey()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); addUserClaims(jwtClaimsSet, request.getAuthorizationReqDTO().getUser()); if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } return signJWT(jwtClaimsSet, request); }
Example #12
Source File: UserInfoJWTResponse.java From carbon-identity with Apache License 2.0 | 5 votes |
@Override public String getResponseString(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException, OAuthSystemException { Map<ClaimMapping, String> userAttributes = getUserAttributesFromCache(tokenResponse); Map<String, Object> claims = null; if (userAttributes.isEmpty()) { if (log.isDebugEnabled()) { log.debug("User attributes not found in cache. Trying to retrieve from user store."); } claims = ClaimUtil.getClaimsFromUserStore(tokenResponse); } else { UserInfoClaimRetriever retriever = UserInfoEndpointConfig.getInstance().getUserInfoClaimRetriever(); claims = retriever.getClaimsMap(userAttributes); } if(claims == null){ claims = new HashMap<String,Object>(); } if(!claims.containsKey("sub") || StringUtils.isBlank((String) claims.get("sub"))) { claims.put("sub", tokenResponse.getAuthorizedUser()); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setAllClaims(claims); return new PlainJWT(jwtClaimsSet).serialize(); }
Example #13
Source File: DefaultIDTokenBuilder.java From carbon-identity with Apache License 2.0 | 4 votes |
@Override public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String issuer = OAuth2Util.getIDTokenIssuer(); long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000; long curTimeInMillis = Calendar.getInstance().getTimeInMillis(); // setting subject String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier(); String nonceValue = request.getAuthorizationReqDTO().getNonce(); // Get access token issued time long accessTokenIssuedTime = getAccessTokenIssuedTime(tokenRespDTO.getAccessToken(), request) / 1000; String atHash = null; String responseType = request.getAuthorizationReqDTO().getResponseType(); //at_hash is generated on access token. Hence the check on response type to be id_token token or code if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()) && !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) && !OAuthConstants.NONE.equalsIgnoreCase(responseType)) { String digAlg = mapDigestAlgorithm(signatureAlgorithm); MessageDigest md; try { md = MessageDigest.getInstance(digAlg); } catch (NoSuchAlgorithmException e) { throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg); } md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8)); byte[] digest = md.digest(); int leftHalfBytes = 16; if (SHA384.equals(digAlg)) { leftHalfBytes = 24; } else if (SHA512.equals(digAlg)) { leftHalfBytes = 32; } byte[] leftmost = new byte[leftHalfBytes]; for (int i = 0; i < leftHalfBytes; i++) { leftmost[i] = digest[i]; } atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8); } if (log.isDebugEnabled()) { StringBuilder stringBuilder = (new StringBuilder()) .append("Using issuer ").append(issuer).append("\n") .append("Subject ").append(subject).append("\n") .append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n") .append("Current time ").append(curTimeInMillis / 1000).append("\n") .append("Nonce Value ").append(nonceValue).append("\n") .append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); if (log.isDebugEnabled()) { log.debug(stringBuilder.toString()); } } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); jwtClaimsSet.setSubject(subject); jwtClaimsSet.setAudience(Arrays.asList(request.getAuthorizationReqDTO().getConsumerKey())); jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey()); jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis)); jwtClaimsSet.setIssueTime(new Date(curTimeInMillis)); jwtClaimsSet.setClaim("auth_time", accessTokenIssuedTime); if(atHash != null){ jwtClaimsSet.setClaim("at_hash", atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim("nonce", nonceValue); } request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken()); CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) { return new PlainJWT(jwtClaimsSet).serialize(); } return signJWT(jwtClaimsSet, request); }