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: pac4j-plus   File: JwtGenerator.java   7 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 2
Project: device-telemetry-java   File: OpenIdConnectJwtValidation.java   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 3
Project: device-telemetry-java   File: OpenIdConnectJwtValidation.java   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 4
Project: Your-Microservice   File: YourMicroserviceToken_nimbus_Impl.java   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 5
Project: azure-spring-boot   File: UserPrincipal.java   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 6
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 7
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 8
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 9
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 10
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 11
Project: simple-openid-provider   File: AuthorizationEndpointTests.java   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 12
Project: simple-openid-provider   File: TokenEndpointTests.java   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 13
Project: simple-openid-provider   File: TokenEndpointTests.java   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 14
Project: simple-openid-provider   File: TokenEndpointTests.java   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 15
Project: digital-display-garden-iteration-4-dorfner-v2   File: Auth.java   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 16
Project: digital-display-garden-iteration-4-dorfner-v2   File: Auth.java   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 17
Project: iothub-manager-java   File: OpenIdConnectJwtValidation.java   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 18
Project: iothub-manager-java   File: OpenIdConnectJwtValidation.java   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 19
Project: diferentonas-server   File: AcessoCidadao.java   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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   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();
}
 
Example 41
Project: shibboleth-oidc   File: ShibbolethAcrAwareTokenService.java   6 votes vote down vote up
/**
 * Encrypt id token.
 *
 * @param client   the client
 * @param idClaims the id claims
 */
private JWT encryptIdToken(final ClientDetailsEntity client, final JWTClaimsSet.Builder idClaims) {
    log.debug("Locating encrypter service for client {}", client.getClientId());
    final JWTEncryptionAndDecryptionService encrypter = encrypters.getEncrypter(client);

    if (encrypter == null) {
        log.error("Couldn't find encrypter for client: {} ", client.getClientId());
        return null;
    }
    log.debug("Found encrypter service for client {}.", client.getClientId());
    final JWTClaimsSet claims = idClaims.build();
    final EncryptedJWT idToken = new EncryptedJWT(new JWEHeader(client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc()), claims);

    log.debug("Encrypting idToken with response alg {} and response encoding {} and claims {}",
            client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc(), claims.getClaims().keySet());
    encrypter.encryptJwt(idToken);
    return idToken;
}
 
Example 42
Project: shibboleth-oidc   File: ShibbolethAcrAwareTokenService.java   6 votes vote down vote up
/**
 * Calculate amr and acr claims.
 *
 * @param accessToken the access token
 * @param idClaims    the id claims
 */
private void calculateAmrAndAcrClaims(final OAuth2AccessTokenEntity accessToken,
                                      final JWTClaimsSet.Builder idClaims) {
    final OAuth2Authentication authN = accessToken.getAuthenticationHolder().getAuthentication();
    final Collection<GrantedAuthority> authorities = authN.getAuthorities();
    for (final GrantedAuthority authority : authorities) {
        log.debug("Evaluating authority {} of the authentication", authority);
        final AuthenticationClassRefAuthority acr =
                AuthenticationClassRefAuthority.getAuthenticationClassRefAuthority(authority);
        if (acr != null) {
            idClaims.claim(OIDCConstants.ACR, acr.getAuthority());
            log.debug("Added {} claim as {}", OIDCConstants.ACR, acr.getAuthority());
        }
        final AuthenticationMethodRefAuthority amr =
                AuthenticationMethodRefAuthority.getAuthenticationClassRefAuthority(authority);
        if (amr != null) {
            idClaims.claim(OIDCConstants.AMR, amr.getAuthority());
            log.debug("Added {} claim as {}", OIDCConstants.AMR, amr.getAuthority());
        }
    }
}
 
Example 43
Project: carbon-identity   File: DefaultIDTokenBuilder.java   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 44
Project: jwt-gen   File: Generator.java   6 votes vote down vote up
private static String getJwt(String subject, String issuer, String secret,
        int expiresInSeconds) throws JOSEException {
    JWSSigner signer = new MACSigner(secret.getBytes());

    JWTClaimsSet claimsSet = new JWTClaimsSet();
    claimsSet.setSubjectClaim(subject);
    claimsSet.setIssuedAtClaim(new Date().getTime());
    claimsSet.setIssuerClaim(issuer);
    claimsSet.setExpirationTimeClaim(new Date().getTime()
            + (expiresInSeconds * 1000));

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

    String jwt = signedJWT.serialize();
    return jwt;
}
 
Example 45
Project: para   File: SecurityUtils.java   6 votes vote down vote up
/**
 * Validates a JWT token.
 * @param secret secret used for generating the token
 * @param jwt token to validate
 * @return true if token is valid
 */
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
	try {
		if (secret != null && jwt != null) {
			JWSVerifier verifier = new MACVerifier(secret);
			if (jwt.verify(verifier)) {
				Date referenceTime = new Date();
				JWTClaimsSet claims = jwt.getJWTClaimsSet();

				Date expirationTime = claims.getExpirationTime();
				Date notBeforeTime = claims.getNotBeforeTime();
				boolean expired = expirationTime == null || expirationTime.before(referenceTime);
				boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);

				return !(expired || notYetValid);
			}
		}
	} catch (JOSEException e) {
		logger.warn(null, e);
	} catch (ParseException ex) {
		logger.warn(null, ex);
	}
	return false;
}
 
Example 46
Project: para   File: SecurityUtils.java   6 votes vote down vote up
/**
 * Generates a new JWT token.
 * @param user a User object belonging to the app
 * @param app the app object
 * @return a new JWT or null
 */
public static SignedJWT generateJWToken(User user, App app) {
	if (app != null) {
		try {
			Date now = new Date();
			JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
			String userSecret = "";
			claimsSet.issueTime(now);
			claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
			claimsSet.notBeforeTime(now);
			claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
			claimsSet.claim(Config._APPID, app.getId());
			if (user != null) {
				claimsSet.subject(user.getId());
				userSecret = user.getTokenSecret();
			}
			JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
			SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
			signedJWT.sign(signer);
			return signedJWT;
		} catch (JOSEException e) {
			logger.warn("Unable to sign JWT: {}.", e.getMessage());
		}
	}
	return null;
}
 
Example 47
Project: AgentWorkbench   File: SimpleOIDCClient.java   5 votes vote down vote up
/**
 * Gets the id claims.
 * 
 * @return the id claims
 * @throws java.text.ParseException
 */
public JWTClaimsSet getIdClaims() {
	try {
		return verifyIdToken();
	} catch (ParseException | java.text.ParseException e) {
		return new JWTClaimsSet.Builder().build(); // return empty claims
	}
}
 
Example 48
Project: cas-5.1.0   File: TokenWebApplicationServiceResponseBuilder.java   5 votes vote down vote up
/**
 * Generate token string.
 *
 * @param service    the service
 * @param parameters the parameters
 * @return the jwt
 */
protected String generateToken(final Service service, final Map<String, String> parameters) {
    try {
        final String ticketId = parameters.get(CasProtocolConstants.PARAMETER_TICKET);
        final Cas30ServiceTicketValidator validator = new Cas30ServiceTicketValidator(casProperties.getServer().getPrefix());
        final Assertion assertion = validator.validate(ticketId, service.getId());
        final JWTClaimsSet.Builder claims =
                new JWTClaimsSet.Builder()
                        .audience(service.getId())
                        .issuer(casProperties.getServer().getPrefix())
                        .jwtID(ticketId)
                        .issueTime(assertion.getAuthenticationDate())
                        .subject(assertion.getPrincipal().getName());
        assertion.getAttributes().forEach(claims::claim);
        assertion.getPrincipal().getAttributes().forEach(claims::claim);

        if (assertion.getValidUntilDate() != null) {
            claims.expirationTime(assertion.getValidUntilDate());
        } else {
            final ZonedDateTime dt = ZonedDateTime.now().plusSeconds(ticketGrantingTicketExpirationPolicy.getTimeToLive());
            claims.expirationTime(DateTimeUtils.dateOf(dt));
        }
        final JWTClaimsSet claimsSet = claims.build();
        final JSONObject object = claimsSet.toJSONObject();
        return tokenCipherExecutor.encode(object.toJSONString());
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
Example 49
Project: spring-boot-actuator-dashboard   File: AccessTokenService.java   5 votes vote down vote up
String generateToken() {
	Instant now = Instant.now();
	Instant exp = now.plus(1, ChronoUnit.DAYS);

	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.issuer(props.getExternalUrl() + "/oauth/token") //
			.expirationTime(Date.from(exp)) //
			.issueTime(Date.from(now)) //
			.claim("scope", Collections.singletonList("actuator.read")) //
			.build();

	return this.jwtTokenConverter.sign(claimsSet).serialize();
}
 
Example 50
Project: spring-boot-actuator-dashboard   File: JwtTokenConverter.java   5 votes vote down vote up
public SignedJWT sign(JWTClaimsSet claimsSet) {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256) //
			.keyID(getKey().get("kid"))//
			.type(JOSEObjectType.JWT) //
			.build();
	SignedJWT signedJWT = new SignedJWT(header, claimsSet);
	try {
		signedJWT.sign(signer);
	}
	catch (JOSEException e) {
		throw new IllegalStateException(e);
	}
	return signedJWT;
}
 
Example 51
Project: microprofile-jwt-auth   File: DebugTest.java   5 votes vote down vote up
@Test(groups = TCKConstants.TEST_GROUP_DEBUG,
    description = "Validate how to use the HS256 signature alg")
public void testHS256() throws Exception {
    JWTClaimsSet claimsSet = JWTClaimsSet.parse("{\"sub\":\"jdoe\"}");
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
    SecureRandom random = new SecureRandom();
    BigInteger secret = BigInteger.probablePrime(256, random);
    JWSSigner signer = new MACSigner(secret.toByteArray());
    signedJWT.sign(signer);
}
 
Example 52
Project: atbash-octopus   File: MPBearerTokenVerifier.java   5 votes vote down vote up
@Override
public boolean verify(JWSHeader header, JWTClaimsSet jwtClaimsSet) {
    boolean result = true;
    if (!jwtClaimsSet.getAudience().contains(mpConfiguration.getAudience())) {
        // TODO Log
        result = false;
    }

    if (jwtClaimsSet.getExpirationTime().before(new Date())) {
        // TODO Log
        result = false;
    }
    return result;
}
 
Example 53
Project: Your-Microservice   File: AuthenticationTokenFilter.java   5 votes vote down vote up
/**
 * doFilter
 * Perform Authorization Access via Token Validation.
 *
 * @param request Reference
 * @param response Reference
 * @param chain Filter Chain
 * @throws java.io.IOException Thrown if IO Exceptions.
 * @throws javax.servlet.ServletException Thrown if Servlet Exceptions.
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    /**
     * Obtain the JWT from the Authorization Header.
     */
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authToken = YourMicroserviceSecurityConstants.obtainAuthorizationBearerToken(httpRequest);
    /**
     * Now Verify the Token and then, obtain the Subject Claim.
     * Validate we have a username from an extracted token and we are not authenticated,
     * then determine if the Token can be fully validated and has not Expired.
     */
    if (authToken != null) {
        try {
            JWTClaimsSet jwtClaimsSet = yourMicroserviceToken.verifyToken(authToken);
            if (jwtClaimsSet != null) {
                /**
                 * Obtain our Subject from the Claims Set, which is our UserName, aka Your Microservice Person's
                 * Primary Email.
                 */
                String username = jwtClaimsSet.getSubject();
                if (username != null && !username.isEmpty() &&
                        SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    /**
                     * Perform Statistical Metric of a Token being Used.
                     */
                     Integer countUpdated =
                             identityProviderEntityManager.incrementTokenHistoryUsage(jwtClaimsSet.getJWTID());
                     if (countUpdated == null || countUpdated != 1) {
                         /**
                          * We did not update the Usage Counter, this indicates that either the
                          * Token has Expired, Revoked or in some other state other than Active,
                          * so, immediately fail this token.
                          */
                         SecurityContextHolder.getContext().setAuthentication(null);
                     }
                }
            }
        } catch (YourMicroserviceInvalidTokenException iste) {
            /**
             * Do Nothing, as the attempt of the failed Token will be Denied...
             */
            SecurityContextHolder.getContext().setAuthentication(null);
            YourMicroserviceToken.LOGGER.warn("{}Invalid Token Denying Access.", YourMicroserviceToken.LOGGING_HEADER);
        }
    }
    /**
     * Continue filter chain.
     */
    chain.doFilter(request, response);
}
 
Example 54
Project: Your-Microservice   File: AuthenticationController.java   5 votes vote down vote up
/**
 * saveTokenHistory
 *
 * @param token Token to re-verify to obtain Claims Set to Persist as a Token History Element.
 */
@Async
protected void saveTokenHistory(String token) {
    try {
        /**
         * Generate a Token History Entry based upon our Current Supplied Token.
         */
        JWTClaimsSet claimsSet = yourMicroserviceToken.verifyToken(token);
        if (claimsSet == null) {
            LOGGER.warn("Unable to Verify Token to retrieve ClaimsSet to Persist Token History, Ignoring.");
            return;
        }
        /**
         * Instantiate the Token History Entity.
         */
        YourEntityTokenHistory yourEntityTokenHistory = new YourEntityTokenHistory();
        yourEntityTokenHistory.setJti(claimsSet.getJWTID());
        yourEntityTokenHistory.setSubject(claimsSet.getSubject());
        yourEntityTokenHistory.setStatus(YourEntityTokenStatus.ACTIVE);
        yourEntityTokenHistory.setIssuedAt(claimsSet.getIssueTime());
        yourEntityTokenHistory.setExpiration(claimsSet.getExpirationTime());
        yourEntityTokenHistory.setNotUsedBefore(claimsSet.getNotBeforeTime());
        yourEntityTokenHistory.setLastUsed(claimsSet.getIssueTime());
        yourEntityTokenHistory.setUsageCount(1L);
        /**
         * Persist the Entity.
         */
        yourEntityTokenHistory = identityProviderEntityManager.createTokenHistory(yourEntityTokenHistory);
        if (yourEntityTokenHistory == null) {
            LOGGER.warn("Unable to Persist Token History Entity, Ignoring.");
        }
    } catch (YourMicroserviceInvalidTokenException ite) {
        LOGGER.warn("Invalid Your Microservice Token Exception:'{}', Encountered while attempting " +
                "to persist Token History Entity.", ite.getMessage(), ite);
    }
}
 
Example 55
Project: Your-Microservice   File: YourMicroserviceToken_nimbus_Impl.java   5 votes vote down vote up
/**
 * getClaimsFromToken
 * <p>
 * Private helper method to obtain all Claims for specified JWT.
 *
 * @param token JWT
 * @return Claims parsed from JWT.
 */
protected Map<String, Object> getClaimsFromToken(String token) {
    try {
        JWTClaimsSet jwtClaimsSet = verifyToken(token);
        if (jwtClaimsSet != null) {
            return jwtClaimsSet.getClaims();
        }
    } catch (Exception e) {
        LOGGER.error("{}Exception Processing Token:'{}', '{}'.", LOGGING_HEADER, token, e.getMessage(), e);
    }
    return null;
}
 
Example 56
Project: marathon-client   File: DCOSAuthCredentials.java   5 votes vote down vote up
private static String signJWT(String uid, PrivateKey privateKey) {
    final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).type(JOSEObjectType.JWT).build();
    final JWTClaimsSet payload = new JWTClaimsSet.Builder().claim("uid", uid).build();
    final SignedJWT signedJWT = new SignedJWT(header, payload);

    try {
        signedJWT.sign(new RSASSASigner(privateKey));
        return signedJWT.serialize();
    } catch (JOSEException e) {
        throw new RuntimeException(e);
    }
}
 
Example 57
Project: simple-openid-provider   File: TokenEndpointTests.java   5 votes vote down vote up
@Test
public void authCode_basicAuth_isOk() throws Exception {
	ClientID clientId = new ClientID("test-client");
	URI redirectUri = URI.create("http://rp.example.com");
	Scope scope = new Scope(OIDCScopeValue.OPENID);
	AuthorizationCode authorizationCode = new AuthorizationCode();

	ClientSecretBasic clientAuth = new ClientSecretBasic(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,
			scope, 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_BASIC));
	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)
			.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
	this.mvc.perform(request).andExpect(status().isOk());
}
 
Example 58
Project: simple-openid-provider   File: TokenEndpointTests.java   5 votes vote down vote up
@Test
public void authCode_mismatchedClientId_shouldThrowException() throws Exception {
	URI redirectUri = URI.create("http://rp.example.com");
	Scope scope = new Scope(OIDCScopeValue.OPENID);
	AuthorizationCode authorizationCode = new AuthorizationCode();

	ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("bad-client"), 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"),
			new ClientID("test-client"), redirectUri, scope, 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_BASIC));
	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)
			.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
	this.mvc.perform(request).andExpect(status().isBadRequest());
}
 
Example 59
Project: simple-openid-provider   File: TokenEndpointTests.java   5 votes vote down vote up
@Test
public void authCode_mismatchedRedirectUri_shouldThrowException() throws Exception {
	ClientID clientId = new ClientID("test-client");
	Scope scope = new Scope(OIDCScopeValue.OPENID);
	AuthorizationCode authorizationCode = new AuthorizationCode();

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

	AuthorizationCodeContext context = new AuthorizationCodeContext(new Subject("user"), clientId,
			URI.create("http://rp.example.com"), scope, 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_BASIC));
	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)
			.header("Authorization", clientAuth.toHTTPAuthorizationHeader());
	this.mvc.perform(request).andExpect(status().isBadRequest());
}
 
Example 60
Project: jsr375-extensions   File: TokenGenerator.java   5 votes vote down vote up
private static String createToken(Info info) {
    JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
    claimsSetBuilder.subject(info.getUserName());

    claimsSetBuilder.issueTime(new Date());
    claimsSetBuilder.expirationTime(new Date(new Date().getTime() + 30 * 1000));

    JSONArray roleValues = new JSONArray();
    roleValues.addAll(info.getRoles());

    Map<String, Object> roles = new HashMap<>();
    roles.put("roles", roleValues);

    claimsSetBuilder.claim("realm_access", roles);

    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS512).type(JOSEObjectType.JWT).keyID(info.getApiKey()).build();
    SignedJWT signedJWT = new SignedJWT(header, claimsSetBuilder.build());

    System.out.println(claimsSetBuilder.build().toJSONObject().toString(JSONStyle.NO_COMPRESS));

    try {
        JWSSigner signer = new RSASSASigner((RSAKey) jwkSet.getKeyByKeyId(info.getApiKey()));

        signedJWT.sign(signer);
    } catch (JOSEException e) {
        // Should not happen
        e.printStackTrace();
    }

    return signedJWT.serialize();
}