Java Code Examples for com.nimbusds.jwt.JWTClaimsSet

The following are top voted examples for showing how to use com.nimbusds.jwt.JWTClaimsSet. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: device-telemetry-java   File: OpenIdConnectJwtValidation.java   View source code 6 votes vote down vote up
/**
 * Check whether the token has been released by the expected issuer
 */
private Boolean validateTokenIssuer(JWTClaimsSet claims) {

    String issuer = claims.getIssuer();
    if (issuer == null) {
        log.error("The authorization token doesn't have an issuer (iss)");
        return false;
    }

    if (issuer.toLowerCase().equals(this.issuer)) {
        return true;
    }

    log.error("The authorization token issuer `{}` doesn't match the expected issuer `{}`",
        issuer, this.issuer);

    return false;
}
 
Example 2
Project: device-telemetry-java   File: OpenIdConnectJwtValidation.java   View source code 6 votes vote down vote up
/**
 * Check whether the token has been released to the expected audience
 */
private boolean validateTokenAudience(JWTClaimsSet claims) {
    List<String> audiences = claims.getAudience();

    if (audiences == null) {
        log.error("The authorization token doesn't have an audience (aud)");
        return false;
    }

    if (audiences.contains(this.audience)) {
        return true;
    }

    log.error("The authorization token audience `{}` doesn't match the expected audience `{}`",
        audiences, this.audience);

    return false;
}
 
Example 3
Project: Your-Microservice   File: YourMicroserviceToken_nimbus_Impl.java   View source code 6 votes vote down vote up
/**
 * parseJWT
 * Parse JWT and  Display Token Information in Logs.
 *
 * @param jwt Token to be Parsed
 */
@Override
public void parseAndDumpJWT(final String jwt) throws Exception {
    /**
     * This line will throw an exception if it is not a signed JWS (as expected)
     */
    JWTClaimsSet claimsSet = verifyToken(jwt);
    if (claimsSet == null) {
        LOGGER.error("{}No Claims Set returned, Invalid Token.",LOGGING_HEADER);
        return;
    }
    LOGGER.info("{} Dumping JWT: '{}'", LOGGING_HEADER, jwt);
    for(String claimKey : claimsSet.getClaims().keySet()) {
        LOGGER.info("{} ++ Claim '{}' = '{}'", LOGGING_HEADER,
                claimKey, claimsSet.getClaims().get(claimKey));
    }
}
 
Example 4
Project: azure-spring-boot   File: UserPrincipal.java   View source code 6 votes vote down vote up
private ConfigurableJWTProcessor<SecurityContext> getAadJwtTokenValidator()
        throws MalformedURLException {
    final ConfigurableJWTProcessor<SecurityContext> jwtProcessor = new DefaultJWTProcessor<>();
    final JWKSource<SecurityContext> keySource = new RemoteJWKSet<>(
            new URL(KEY_DISCOVERY_URI));
    final JWSAlgorithm expectedJWSAlg = JWSAlgorithm.RS256;
    final JWSKeySelector<SecurityContext> keySelector = new JWSVerificationKeySelector<>(expectedJWSAlg, keySource);
    jwtProcessor.setJWSKeySelector(keySelector);

    jwtProcessor.setJWTClaimsSetVerifier(new DefaultJWTClaimsVerifier<SecurityContext>() {
        @Override
        public void verify(JWTClaimsSet claimsSet, SecurityContext ctx) throws BadJWTException {
            super.verify(claimsSet, ctx);
            final String issuer = claimsSet.getIssuer();
            if (issuer == null || !issuer.contains("https://sts.windows.net/")) {
                throw new BadJWTException("Invalid token issuer");
            }
        }
    });
    return jwtProcessor;
}
 
Example 5
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void implicitWithIdTokenAndToken_minimumParams_isSuccess() throws Exception {
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(implicitWithIdTokenAndTokenClient());
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test")
					.session(this.session);
	this.mvc.perform(request).andExpect(status().isFound())
			.andExpect(redirectedUrlTemplate(
					"http://example.com#access_token={accessToken}&id_token={idToken}&token_type=Bearer",
					accessToken.getValue(), idToken.serialize()));
}
 
Example 6
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void implicitWithIdToken_minimumParams_isSuccess() throws Exception {
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(implicitWithIdTokenClient());
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=id_token&client_id=test-client&redirect_uri=http://example.com&nonce=test")
					.session(this.session);
	this.mvc.perform(request).andExpect(status().isFound())
			.andExpect(redirectedUrlTemplate("http://example.com#id_token={idToken}", idToken.serialize()));
}
 
Example 7
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void implicitWithIdTokenAndToken_withState_isSuccess() throws Exception {
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
	State state = new State();

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(implicitWithIdTokenAndTokenClient());
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test&state="
					+ state.getValue()).session(this.session);
	this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate(
			"http://example.com#access_token={accessToken}&id_token={idToken}&state={state}&token_type=Bearer",
			accessToken.getValue(), idToken.serialize(), state.getValue()));
}
 
Example 8
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void hybridWithIdTokenAndToken_minimumParams_isSuccess() throws Exception {
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
	AuthorizationCode authorizationCode = new AuthorizationCode();

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithIdTokenAndTokenClient());
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=code id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test")
					.session(this.session);
	this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate(
			"http://example.com#access_token={accessToken}&code={code}&id_token={idToken}&token_type=Bearer",
			accessToken.getValue(), authorizationCode.getValue(), idToken.serialize()));
}
 
Example 9
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void hybridWithIdToken_minimumParams_isSuccess() throws Exception {
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
	AuthorizationCode authorizationCode = new AuthorizationCode();

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithIdTokenClient());
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=code id_token&client_id=test-client&redirect_uri=http://example.com&nonce=test")
					.session(this.session);
	this.mvc.perform(request).andExpect(status().isFound())
			.andExpect(redirectedUrlTemplate("http://example.com#code={code}&id_token={idToken}",
					authorizationCode.getValue(), idToken.serialize()));
}
 
Example 10
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void hybridWithIdTokenAndToken_withState_isSuccess() throws Exception {
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());
	AuthorizationCode authorizationCode = new AuthorizationCode();
	State state = new State();

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(hybridWithIdTokenAndTokenClient());
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);
	given(this.authorizationCodeService.create(any(AuthorizationCodeContext.class))).willReturn(authorizationCode);
	given(this.subjectResolver.resolveSubject(any(HttpServletRequest.class))).willReturn(new Subject("user"));
	given(this.scopeResolver.resolve(any(Subject.class), any(Scope.class), any(OIDCClientMetadata.class)))
			.will(returnsSecondArg());

	MockHttpServletRequestBuilder request = get(
			"/oauth2/authorize?scope=openid&response_type=code id_token token&client_id=test-client&redirect_uri=http://example.com&nonce=test&state="
					+ state.getValue()).session(this.session);
	this.mvc.perform(request).andExpect(status().isFound()).andExpect(redirectedUrlTemplate(
			"http://example.com#access_token={accessToken}&code={code}&id_token={idToken}&state={state}&token_type=Bearer",
			accessToken.getValue(), authorizationCode.getValue(), idToken.serialize(), state.getValue()));
}
 
Example 11
Project: simple-openid-provider   File: TokenEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void authCode_postAuth_isOk() throws Exception {
	ClientID clientId = new ClientID("test-client");
	URI redirectUri = URI.create("http://rp.example.com");
	AuthorizationCode authorizationCode = new AuthorizationCode();

	ClientSecretPost clientAuth = new ClientSecretPost(clientId, new Secret("test-secret"));
	TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientAuth,
			new AuthorizationCodeGrant(authorizationCode, redirectUri));

	AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
			new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"), null,
			null, null);
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());

	given(this.clientRepository.findById(any(ClientID.class)))
			.willReturn(client(ClientAuthenticationMethod.CLIENT_SECRET_POST));
	given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);

	MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
			.contentType(MediaType.APPLICATION_FORM_URLENCODED);
	this.mvc.perform(request).andExpect(status().isOk());
}
 
Example 12
Project: simple-openid-provider   File: TokenEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void authCode_pkcePlain_isOk() throws Exception {
	ClientID clientId = new ClientID("test-client");
	URI redirectUri = URI.create("http://rp.example.com");
	CodeVerifier codeVerifier = new CodeVerifier();
	CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.PLAIN;
	AuthorizationCode authorizationCode = new AuthorizationCode();

	TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId,
			new AuthorizationCodeGrant(authorizationCode, redirectUri, codeVerifier));

	AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
			new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"),
			CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null);
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE));
	given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);

	MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
			.contentType(MediaType.APPLICATION_FORM_URLENCODED);
	this.mvc.perform(request).andExpect(status().isOk());
}
 
Example 13
Project: simple-openid-provider   File: TokenEndpointTests.java   View source code 6 votes vote down vote up
@Test
public void authCode_pkceS256_isOk() throws Exception {
	ClientID clientId = new ClientID("test-client");
	URI redirectUri = URI.create("http://rp.example.com");
	CodeVerifier codeVerifier = new CodeVerifier();
	CodeChallengeMethod codeChallengeMethod = CodeChallengeMethod.S256;
	AuthorizationCode authorizationCode = new AuthorizationCode();

	TokenRequest tokenRequest = new TokenRequest(URI.create("http://op.example.com"), clientId,
			new AuthorizationCodeGrant(authorizationCode, URI.create("http://rp.example.com"), codeVerifier));

	AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId, redirectUri,
			new Scope(OIDCScopeValue.OPENID), Instant.now(), new ACR("1"), AMR.PWD, new SessionID("test"),
			CodeChallenge.compute(codeChallengeMethod, codeVerifier), codeChallengeMethod, null);
	BearerAccessToken accessToken = new BearerAccessToken();
	JWT idToken = new PlainJWT(new JWTClaimsSet.Builder().build());

	given(this.clientRepository.findById(any(ClientID.class))).willReturn(client(ClientAuthenticationMethod.NONE));
	given(this.authorizationCodeService.consume(eq(authorizationCode))).willReturn(context);
	given(this.tokenService.createAccessToken(any(AccessTokenRequest.class))).willReturn(accessToken);
	given(this.tokenService.createIdToken(any(IdTokenRequest.class))).willReturn(idToken);

	MockHttpServletRequestBuilder request = post("/oauth2/token").content(tokenRequest.toHTTPRequest().getQuery())
			.contentType(MediaType.APPLICATION_FORM_URLENCODED);
	this.mvc.perform(request).andExpect(status().isOk());
}
 
Example 14
Project: digital-display-garden-iteration-4-dorfner-v2   File: Auth.java   View source code 6 votes vote down vote up
String generateCookieBody(int secondsToLive) {
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    JWSSigner signer = new RSASSASigner(privateKey);

    DateTime expDate = new DateTime((new Date()).getTime() + secondsToLive * 1000);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .issuer("digital-display-garden")
            .claim("exp", expDate.toString())
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader(JWSAlgorithm.RS256),
            claimsSet
    );
    try {
        signedJWT.sign(signer);
        return signedJWT.serialize();
    } catch (JOSEException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 15
Project: digital-display-garden-iteration-4-dorfner-v2   File: Auth.java   View source code 6 votes vote down vote up
String generateSharedGoogleSecret(String originatingURL) {
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    JWSSigner signer = new RSASSASigner(privateKey);

    // Expire in 60 seconds
    DateTime expDate = new DateTime((new Date()).getTime() + 60 * 1000);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .issuer("digital-display-garden")
            .claim("originatingURL", originatingURL)
            .claim("exp", expDate.toString())
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader(JWSAlgorithm.RS256),
            claimsSet
    );
    try {
        signedJWT.sign(signer);
        return signedJWT.serialize();
    } catch (JOSEException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 16
Project: iothub-manager-java   File: OpenIdConnectJwtValidation.java   View source code 6 votes vote down vote up
/**
 * Check whether the token has been released by the expected issuer
 */
private Boolean validateTokenIssuer(JWTClaimsSet claims) {

    String issuer = claims.getIssuer();
    if (issuer == null) {
        log.error("The authorization token doesn't have an issuer (iss)");
        return false;
    }

    if (issuer.toLowerCase().equals(this.issuer)) {
        return true;
    }

    log.error("The authorization token issuer `{}` doesn't match the expected issuer `{}`",
        issuer, this.issuer);

    return false;
}
 
Example 17
Project: iothub-manager-java   File: OpenIdConnectJwtValidation.java   View source code 6 votes vote down vote up
/**
 * Check whether the token has been released to the expected audience
 */
private boolean validateTokenAudience(JWTClaimsSet claims) {
    List<String> audiences = claims.getAudience();

    if (audiences == null) {
        log.error("The authorization token doesn't have an audience (aud)");
        return false;
    }

    if (audiences.contains(this.audience)) {
        return true;
    }

    log.error("The authorization token audience `{}` doesn't match the expected audience `{}`",
        audiences, this.audience);

    return false;
}
 
Example 18
Project: pac4j-plus   File: JwtGenerator.java   View source code 6 votes vote down vote up
protected JWTClaimsSet buildJwtClaimsSet(final U profile) {
    // claims builder with subject and issue time
    final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
            .subject(profile.getTypedId())
            .issueTime(new Date());

    // add attributes
    final Map<String, Object> attributes = profile.getAttributes();
    for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
        builder.claim(entry.getKey(), entry.getValue());
    }
    builder.claim(INTERNAL_ROLES, profile.getRoles());
    builder.claim(INTERNAL_PERMISSIONS, profile.getPermissions());

    // claims
    return builder.build();
}
 
Example 19
Project: diferentonas-server   File: AcessoCidadao.java   View source code 6 votes vote down vote up
@Override
 public String getUsername(Context ctx) {
 	String[] authTokenHeaderValues = ctx.request().headers().get(AuthUtils.AUTH_HEADER_KEY);
 	if ((authTokenHeaderValues != null) && (authTokenHeaderValues.length == 1) && (authTokenHeaderValues[0] != null)) {
 		String authHeader = authTokenHeaderValues[0];

try {
	JWTClaimsSet claimSet = (JWTClaimsSet) authenticator.decodeToken(authHeader);
	if (new DateTime(claimSet.getExpirationTime()).isAfter(DateTime.now())) {
		return claimSet.getSubject();
	} 
} catch (ParseException | JOSEException e) {
	Logger.error("Erro na validação do token: " + e.getMessage());
}
 	}

     return null;
 }
 
Example 20
Project: aliyun-oss-hadoop-fs   File: TestJWTRedirectAuthentictionHandler.java   View source code 6 votes vote down vote up
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey)
    throws Exception {
  JWTClaimsSet claimsSet = new JWTClaimsSet();
  claimsSet.setSubject(sub);
  claimsSet.setIssueTime(new Date(new Date().getTime()));
  claimsSet.setIssuer("https://c2id.com");
  claimsSet.setCustomClaim("scope", "openid");
  claimsSet.setExpirationTime(expires);
  List<String> aud = new ArrayList<String>();
  aud.add("bar");
  claimsSet.setAudience("bar");

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();

  SignedJWT signedJWT = new SignedJWT(header, claimsSet);
  Base64URL sigInput = Base64URL.encode(signedJWT.getSigningInput());
  JWSSigner signer = new RSASSASigner(privateKey);

  signedJWT.sign(signer);

  return signedJWT;
}
 
Example 21
Project: PrOfESSOS   File: AbstractOPImplementation.java   View source code 6 votes vote down vote up
protected JWTClaimsSet getIdTokenClaims(@Nonnull ClientID clientId, @Nullable Nonce nonce,
		@Nullable AccessTokenHash atHash, @Nullable CodeHash cHash) throws ParseException {
	UserInfo ui = getUserInfo();

	JWTClaimsSet.Builder cb = new JWTClaimsSet.Builder(ui.toJWTClaimsSet());

	cb.issuer(getTokenIssuer().getValue());
	cb.audience(getTokenAudience(clientId));
	cb.issueTime(getTokenIssuedAt());
	cb.expirationTime(getTokenExpiration());

	if (nonce != null) {
		cb.claim("nonce", nonce.getValue());
	}
	if (atHash != null) {
		cb.claim("at_hash", atHash.getValue());
	}
	if (cHash != null) {
		cb.claim("c_hash", cHash.getValue());
	}

	JWTClaimsSet claims = cb.build();
	return claims;
}
 
Example 22
Project: PrOfESSOS   File: AbstractOPImplementation.java   View source code 6 votes vote down vote up
protected JWT getIdToken(@Nonnull ClientID clientId, @Nullable Nonce nonce, @Nullable AccessTokenHash atHash,
		@Nullable CodeHash cHash) throws GeneralSecurityException, JOSEException, ParseException {
	JWTClaimsSet claims = getIdTokenClaims(clientId, nonce, atHash, cHash);

	RSAKey key = getSigningJwk();

	JWSHeader.Builder headerBuilder = new JWSHeader.Builder(JWSAlgorithm.RS256)
			.type(JOSEObjectType.JWT);
	if (params.getBool(INCLUDE_SIGNING_CERT)) {
		headerBuilder = headerBuilder.jwk(key.toPublicJWK());
	}
	JWSHeader header = headerBuilder.build();

	SignedJWT signedJwt = new SignedJWT(header, claims);

	JWSSigner signer = new RSASSASigner(key);
	signedJwt.sign(signer);

	return signedJwt;
}
 
Example 23
Project: otus-api   File: SecurityContextServiceBeanTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
	secretKey = TOKEN.getBytes();
	sessionIdentifier = spy(new SessionIdentifier(TOKEN, secretKey, authenticationData));
	signer = new MACSigner(secretKey);
	whenNew(MACSigner.class).withArguments(secretKey).thenReturn(signer);

	JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
	builder.issuer(USER);
	builder.claim("mode", MODE);
	JWTClaimsSet buildClaim = builder.build();
	when(authenticationData.buildClaimSet()).thenReturn(buildClaim);

	jwsHeader = new JWSHeader(JWSAlgorithm.HS256);
	signedJWT = spy(new SignedJWT(jwsHeader, buildClaim));
	whenNew(SignedJWT.class).withAnyArguments().thenReturn(signedJWT);

}
 
Example 24
Project: swarm-oidc   File: OIDCAuthenticationMechanism.java   View source code 6 votes vote down vote up
protected AuthenticationMechanismOutcome complete(JWTClaimsSet claims, AccessToken accessToken, String returnURL, HttpServerExchange exchange, boolean redirect) throws Exception {
	OIDCPrincipal principal = new OIDCPrincipalExt(claims, accessToken);
	Account account = new AccountImpl(principal);
	account = identityManager.verify(account);
	if (account == null) {
		LOG.warning(String.format("OIDC subject %s not found in identity manager", principal.getName()));
		exchange.getSecurityContext().authenticationFailed("OIDC subject not found in identity manager", mechanismName);
		OIDCContext oidcContext = exchange.getAttachment(OIDCContext.ATTACHMENT_KEY);
		oidcContext.setError(true);
		return AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
	}
	exchange.getSecurityContext().authenticationComplete(account, mechanismName, true);
	if (redirect) {
		exchange.getResponseHeaders().put(Headers.LOCATION, returnURL != null && !returnURL.isEmpty() ? returnURL : "/");
		exchange.setStatusCode(HttpServletResponse.SC_FOUND);
		exchange.endExchange();
	}
	LOG.fine("authentificated " + principal);
	return AuthenticationMechanismOutcome.AUTHENTICATED;
}
 
Example 25
Project: roles-auths-client   File: JwtUtil.java   View source code 6 votes vote down vote up
public SignedJWT parseAndVerifyToken(String jwtString) throws WebApiClientException {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwtString);

        JWSVerifier verifier = new RSASSAVerifier(jwtConfig.getRSAPublicKey());
        if (signedJWT.verify(verifier)) {
            JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
            if (claimsSet.getAudience().contains(jwtConfig.getServiceUUID()) &&
                    claimsSet.getIssuer().equalsIgnoreCase(JwtUtil.ISSUER)) {
                return signedJWT;
            }
        }
    } catch (ParseException | JOSEException e) {
        throw new WebApiClientException(e.getMessage());
    }
    throw new WebApiClientException("Authorization token cannot be verified");
}
 
Example 26
Project: mycore   File: MCRJSONWebTokenUtil.java   View source code 6 votes vote down vote up
/**
 * creates an empty JSON Web Token
 * 
 * @param webAppBaseURL - the base url of the application
 * 
 * @return the JSON WebToken
 */
public static SignedJWT createEmptyJWTwithPublicKey(String webAppBaseURL) {

    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
        .issueTime(Date.from(currentTime.toInstant())).build();
    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        LOGGER.error(e);
    }
    return signedJWT;

}
 
Example 27
Project: mycore   File: MCRJSONWebTokenUtil.java   View source code 6 votes vote down vote up
/**
 * creates a JSON Web Token with user id, roles and client public key
 * 
 * @param user - the user that should be returned
 * @param roles - the roles that should be returned
 * @param webAppBaseURL - the base url of the application
 * @param clientPublicKey -  the client public key as JSON Web Key
 * 
 * @return the JSON WebToken
 */
public static SignedJWT createJWT(String user, List<String> roles, String webAppBaseURL, JWK clientPublicKey) {
    ZonedDateTime currentTime = ZonedDateTime.now(ZoneOffset.UTC);
    JWTClaimsSet claims = new JWTClaimsSet.Builder().issuer(webAppBaseURL).jwtID(UUID.randomUUID().toString())
        .expirationTime(Date.from(currentTime.plusMinutes(EXPIRATION_TIME_MINUTES).toInstant()))
        .issueTime(Date.from(currentTime.toInstant()))
        .notBeforeTime(Date.from(currentTime.minusMinutes(EXPIRATION_TIME_MINUTES).toInstant())).subject(user)
        // additional claims/attributes about the subject can be added
        // claims.setClaim("email", "[email protected]");
        // multi-valued claims work too and will end up as a JSON array
        .claim("roles", roles).claim("sub_jwk", clientPublicKey).build();

    String keyID = UUID.randomUUID().toString();
    JWK jwk = new RSAKey.Builder((RSAPublicKey) RSA_KEYS.getPublic()).keyID(keyID).build();
    JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.RS256).jwk(jwk).build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, claims);
    try {
        signedJWT.sign(new RSASSASigner(RSA_KEYS.getPrivate()));
    } catch (JOSEException e) {
        // TODO Auto-generated catch block
        LOGGER.error(e);
    }
    System.out.println("JWT: " + signedJWT.serialize());
    return signedJWT;
}
 
Example 28
Project: base   File: TokenUtil.java   View source code 6 votes vote down vote up
public static String createToken( String headerJson, String claimJson, String sharedKey )
{
    try
    {
        JWSHeader header = JWSHeader.parse( headerJson );
        JWSSigner signer = new MACSigner( sharedKey.getBytes() );
        JWTClaimsSet claimsSet = JWTClaimsSet.parse( claimJson );

        SignedJWT signedJWT = new SignedJWT( header, claimsSet );
        signedJWT.sign( signer );

        return signedJWT.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating token", e.getMessage() );

        return "";
    }
}
 
Example 29
Project: java-cloud-sdk   File: JsonWebToken.java   View source code 6 votes vote down vote up
public String selfIssue() {
	JWSSigner signer = new RSASSASigner((RSAPrivateKey) keyPair.getPrivate());

	List<String> aud = new ArrayList<String>();
	aud.add(Constants.POYNT_API_HOST);

	JWTClaimsSet claimsSet = new JWTClaimsSet();
	claimsSet.setAudience(aud);
	claimsSet.setSubject(config.getAppId());
	claimsSet.setIssuer(config.getAppId());
	Calendar now = Calendar.getInstance();
	claimsSet.setIssueTime(now.getTime());
	now.add(Calendar.MINUTE, 15);
	claimsSet.setExpirationTime(now.getTime());
	claimsSet.setJWTID(UUID.randomUUID().toString());

	SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);

	try {
		signedJWT.sign(signer);
	} catch (JOSEException e) {
		throw new PoyntSdkException("Failed to sign self issued JWT.");
	}
	return signedJWT.serialize();
}
 
Example 30
Project: spring-security-token-filter   File: JwtTokenService.java   View source code 6 votes vote down vote up
@Override
public Optional<Authentication> verifyToken(Optional<String> token) {
  if (!token.isPresent()) {
    return Optional.empty();
  }

  SignedJWT signedJwt;
  JWTClaimsSet claimSet;
  try {
    signedJwt = SignedJWT.parse(token.get());
    claimSet = signedJwt.getJWTClaimsSet();

    if (!signedJwt.verify(verifier)) {
      throw new BadCredentialsException("Invalid token");
    }
  } catch (ParseException | JOSEException e) {
    throw new IllegalArgumentException("Error while parsing and verifying token.", e);
  }


  if (claimSet.getExpirationTime().getTime() < System.currentTimeMillis()) {
    throw new BadCredentialsException("Token is expired");
  }

  return Optional.of(transformer.getAuthentication(claimSet));
}
 
Example 31
Project: spring-security-token-filter   File: UsernamePasswordAuthenticationTokenJwtClaimsSetTransformer.java   View source code 6 votes vote down vote up
@Override
public JWTClaimsSet getClaimsSet(Authentication auth) {
  UserDetails user = (UserDetails) auth.getPrincipal();
  long now = System.currentTimeMillis();

  List<String> roles = user.getAuthorities().stream()
    .map(a -> {
      String role = a.getAuthority();
      if (rolePrefix.isPresent()) {
        role = role.substring(rolePrefix.get().length(), role.length());
      }
      return role;
    })
    .collect(Collectors.toList());

  return new JWTClaimsSet.Builder()
      .subject(user.getUsername())
      .issueTime(new Date(now))
      .expirationTime(new Date(now + tokenDuration))
      .claim(ROLES_FIELD, roles)
      .build();
}
 
Example 32
Project: spring-security-token-filter   File: JwtTokenServiceTest.java   View source code 6 votes vote down vote up
@Test
public void itShouldGenerateAValidToken() throws ParseException, JOSEException {
  JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
      .subject(USER.getUsername())
      .issueTime(NOW)
      .expirationTime(EXPIRATION)
      .build();

  Mockito.when(mockTransformer.getClaimsSet(AUTHENTICATION)).thenReturn(claimsSet);
  Mockito.when(mockSigner.sign(Matchers.any(), Matchers.any())).thenReturn(Base64URL.encode("MYSIGNATURE"));

  // Method being tested
  String token = jwtTokenService.generateToken(AUTHENTICATION);

  SignedJWT signedJwt = SignedJWT.parse(token);
  JWTClaimsSet fetchedClaimsSet = signedJwt.getJWTClaimsSet();

  Assertions.assertThat(signedJwt.verify(verifier)).isTrue();
  System.out.println(signedJwt.serialize());
  Assertions.assertThat(fetchedClaimsSet.getSubject()).isEqualTo(USERNAME);
}
 
Example 33
Project: spring-security-token-filter   File: JwtTokenServiceTest.java   View source code 6 votes vote down vote up
@Test(expected=RuntimeException.class)
public void itShouldThrowExceptionIfSigningFails() throws Exception {
  Set<JWSAlgorithm> algorithms = new HashSet<>();
  algorithms.add(JWSAlgorithm.HS256);
  Mockito.when(mockSigner.supportedJWSAlgorithms()).thenReturn(algorithms);

  jwtTokenService = new JwtTokenService(mockTransformer, mockSigner, mockVerifier);

  JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
      .subject(USER.getUsername())
      .issueTime(NOW)
      .expirationTime(EXPIRATION)
      .build();

  Mockito.when(mockTransformer.getClaimsSet(AUTHENTICATION)).thenReturn(claimsSet);
  Mockito.when(mockSigner.sign(Matchers.any(), Matchers.any())).thenThrow(new JOSEException("Signing fail"));

  // Method being tested
  jwtTokenService.generateToken(AUTHENTICATION);
}
 
Example 34
Project: msf4j   File: JWTAccessTokenBuilder.java   View source code 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param jwtClaimsSet contains JWT body
 * @param request
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example 35
Project: shiro-jwt   File: UserRepository.java   View source code 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example 36
Project: shiro-jwt   File: MACVerifierExtendedTest.java   View source code 6 votes vote down vote up
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
Example 37
Project: shiro-jwt   File: MACVerifierExtendedTest.java   View source code 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example 38
Project: shiro-jwt   File: MACVerifierExtendedTest.java   View source code 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example 39
Project: hops   File: TestJWTRedirectAuthentictionHandler.java   View source code 6 votes vote down vote up
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey)
    throws Exception {
  JWTClaimsSet claimsSet = new JWTClaimsSet();
  claimsSet.setSubject(sub);
  claimsSet.setIssueTime(new Date(new Date().getTime()));
  claimsSet.setIssuer("https://c2id.com");
  claimsSet.setCustomClaim("scope", "openid");
  claimsSet.setExpirationTime(expires);
  List<String> aud = new ArrayList<String>();
  aud.add("bar");
  claimsSet.setAudience("bar");

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();

  SignedJWT signedJWT = new SignedJWT(header, claimsSet);
  JWSSigner signer = new RSASSASigner(privateKey);

  signedJWT.sign(signer);

  return signedJWT;
}
 
Example 40
Project: swagger-cxf-rest-skeleton   File: AuthenticationTokenService.java   View source code 6 votes vote down vote up
private String generateJWT(final String username) throws JOSEException {
	// Create HMAC signer
	final JWSSigner signer = new MACSigner(secret);

	// Prepare JWT with claims set
	final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(username).expirationTime(new Date(new Date().getTime() + 60 * 1000)).claim("http://localhost:8080/", true).build();

	final SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);

	// Apply the HMAC protection
	signedJWT.sign(signer);

	// Serialize to compact form, produces something like
	// eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NDMzODA1NDAsInN1YiI6ImNpZGlhbiIsImh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC8iOnRydWV9.EkPxd0EfujgLrk35DX1XmvnmyJsFO8dqbnzsgg78coM
	return signedJWT.serialize();
}