use of org.jose4j.jwt.consumer.JwtConsumer in project wildfly-swarm by wildfly-swarm.
the class JWTCredential method getName.
/**
* This just parses the token without validation to extract one of the following in order to obtain
* the name to be used for the principal:
* upn
* preferred_username
* subject
*
* If there is an exception it sets the name to INVALID_TOKEN_NAME and saves the exception for access
* via {@link #getJwtException()}
*
* @return the name to use for the principal
*/
public String getName() {
if (name == null) {
name = "INVALID_TOKEN_NAME";
try {
// Build a JwtConsumer that doesn't check signatures or do any validation.
JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
// The first JwtConsumer is basically just used to parse the JWT into a JwtContext object.
JwtContext jwtContext = firstPassJwtConsumer.process(bearerToken);
JwtClaims claimsSet = jwtContext.getJwtClaims();
// We have to determine the unique name to use as the principal name. It comes from upn, preferred_username, sub in that order
name = claimsSet.getClaimValue("upn", String.class);
if (name == null) {
name = claimsSet.getClaimValue("preferred_username", String.class);
if (name == null) {
name = claimsSet.getSubject();
}
}
} catch (Exception e) {
jwtException = e;
}
}
return name;
}
use of org.jose4j.jwt.consumer.JwtConsumer in project digilib by robcast.
the class OpenIdAuthnOps method init.
/* (non-Javadoc)
* @see digilib.auth.AuthnOps#init(digilib.conf.DigilibConfiguration)
*/
@Override
public void init(DigilibConfiguration dlConfig) throws AuthOpException {
configFile = dlConfig.getAsFile("auth-file");
logger.debug("openidauthnops.init (" + configFile + ")");
List<Map<String, String>> idpList;
try {
// load identity providers
XMLMapListLoader idpLoader = new XMLMapListLoader("digilib-oauth", "openid");
idpList = idpLoader.loadUri(configFile.toURI());
} catch (Exception e) {
throw new AuthOpException("ERROR loading auth config file: " + e);
}
if (idpList == null) {
throw new AuthOpException("ERROR unable to load auth config file!");
}
// create Map of roles by issuer
idpRoles = new HashMap<String, List<String>>();
// build a first pass JwtConsumer that doesn't check signatures or do any validation.
firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators().setDisableRequireSignature().setSkipSignatureVerification().build();
// create Map of configured JwtConsumers by issuer
idpJwtConsumers = new HashMap<String, JwtConsumer>();
for (Map<String, String> idpDesc : idpList) {
String issuer = idpDesc.get("issuer");
if (issuer == null) {
logger.error("Missing issuer in openid tag!");
continue;
}
String clientid = idpDesc.get("clientid");
if (clientid == null) {
logger.error("Missing clientid in openid tag! (issuer: " + issuer + ")");
continue;
}
String rolestr = idpDesc.get("roles");
if (rolestr == null) {
logger.error("Missing roles in openid tag! (issuer: " + issuer + ")");
continue;
}
// split roles string into list
List<String> roles = Arrays.asList(rolestr.split(","));
String keytype = idpDesc.get("keytype");
if (keytype == null || !keytype.equals("jwk")) {
logger.error("Missing or invalid keytype in openid tag! (issuer: " + issuer + ")");
continue;
}
String keyData = idpDesc.get("_text");
if (keyData == null || keyData.length() == 0) {
logger.error("Missing key data in openid tag! (issuer: " + issuer + ")");
continue;
}
try {
// create key from JWK data
JsonWebKey jwk = JsonWebKey.Factory.newJwk(keyData);
// create second pass consumer for validation
JwtConsumer secondPassJwtConsumer = new JwtConsumerBuilder().setExpectedIssuer(issuer).setVerificationKey(jwk.getKey()).setRequireExpirationTime().setAllowedClockSkewInSeconds(300).setRequireSubject().setExpectedAudience(clientid).build();
// save consumer and roles
idpJwtConsumers.put(issuer, secondPassJwtConsumer);
idpRoles.put(issuer, roles);
logger.debug("Registered id provider '" + issuer + "'");
} catch (JoseException e) {
logger.error("Invalid key data in openid tag! (issuer: " + issuer + ")");
continue;
}
}
// set token cookie name
tokenCookieName = dlConfig.getAsString("authn-token-cookie");
}
use of org.jose4j.jwt.consumer.JwtConsumer in project tomee by apache.
the class PublicKeyAsJWKSTest method validateJWKS.
@Test
public void validateJWKS() throws Exception {
System.setProperty(Names.VERIFIER_PUBLIC_KEY, "");
System.setProperty(Names.VERIFIER_PUBLIC_KEY_LOCATION, "file://" + Paths.get("").toAbsolutePath().toString() + "/src/test/resources/signer-keyset4k.jwk");
System.setProperty(Names.ISSUER, TCKConstants.TEST_ISSUER);
final PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey4k.pem");
final String kid = "publicKey4k";
final String token = TokenUtils.generateTokenString(privateKey, kid, "/Token1.json", null, new HashMap<>());
System.out.println("token = " + token);
final JWTAuthConfigurationProperties JWTAuthConfigurationProperties = new JWTAuthConfigurationProperties();
JWTAuthConfigurationProperties.init(null);
final JWTAuthConfiguration jwtAuthConfiguration = JWTAuthConfigurationProperties.getJWTAuthConfiguration().orElseThrow(IllegalArgumentException::new);
final JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder().setRequireExpirationTime().setRequireSubject().setSkipDefaultAudienceValidation().setExpectedIssuer(jwtAuthConfiguration.getIssuer()).setJwsAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, RSA_USING_SHA256)).setSkipDefaultAudienceValidation().setVerificationKey(jwtAuthConfiguration.getPublicKey());
if (jwtAuthConfiguration.getExpGracePeriodSecs() > 0) {
jwtConsumerBuilder.setAllowedClockSkewInSeconds(jwtAuthConfiguration.getExpGracePeriodSecs());
} else {
jwtConsumerBuilder.setEvaluationTime(NumericDate.fromSeconds(0));
}
if (jwtAuthConfiguration.isSingleKey()) {
jwtConsumerBuilder.setVerificationKey(jwtAuthConfiguration.getPublicKey());
} else {
jwtConsumerBuilder.setVerificationKeyResolver(new JwksVerificationKeyResolver(jwtAuthConfiguration.getPublicKeys()));
}
final JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
final JwtContext jwtContext = jwtConsumer.process(token);
Assert.assertEquals(jwtContext.getJwtClaims().getStringClaimValue("upn"), "jdoe@example.com");
}
use of org.jose4j.jwt.consumer.JwtConsumer in project blueocean-plugin by jenkinsci.
the class JwtAuthenticationServiceImplTest method anonymousUserToken.
@Test
public void anonymousUserToken() throws Exception {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
JenkinsRule.WebClient webClient = j.createWebClient();
String token = getToken(webClient);
Assert.assertNotNull(token);
JsonWebStructure jsonWebStructure = JsonWebStructure.fromCompactSerialization(token);
Assert.assertTrue(jsonWebStructure instanceof JsonWebSignature);
JsonWebSignature jsw = (JsonWebSignature) jsonWebStructure;
String kid = jsw.getHeader("kid");
Assert.assertNotNull(kid);
Page page = webClient.goTo("jwt-auth/jwks/" + kid + "/", "application/json");
// for(NameValuePair valuePair: page.getWebResponse().getResponseHeaders()){
// System.out.println(valuePair);
// }
JSONObject jsonObject = JSONObject.fromObject(page.getWebResponse().getContentAsString());
RsaJsonWebKey rsaJsonWebKey = new RsaJsonWebKey(jsonObject, null);
JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime().setAllowedClockSkewInSeconds(// allow some leeway in validating time based claims to account for clock skew
30).setRequireSubject().setVerificationKey(// verify the sign with the public key
rsaJsonWebKey.getKey()).build();
JwtClaims claims = jwtConsumer.processToClaims(token);
Assert.assertEquals("anonymous", claims.getSubject());
Map<String, Object> claimMap = claims.getClaimsMap();
Map<String, Object> context = (Map<String, Object>) claimMap.get("context");
Map<String, String> userContext = (Map<String, String>) context.get("user");
Assert.assertEquals("anonymous", userContext.get("id"));
}
Aggregations