org.eclipse.microprofile.jwt.JsonWebToken Java Examples

The following examples show how to use org.eclipse.microprofile.jwt.JsonWebToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MpJwtValidator.java    From quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TokenAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return Uni.createFrom().emitter(new Consumer<UniEmitter<? super SecurityIdentity>>() {
        @Override
        public void accept(UniEmitter<? super SecurityIdentity> uniEmitter) {
            try {
                JsonWebToken jwtPrincipal = parser.parse(request.getToken().getToken());
                uniEmitter.complete(QuarkusSecurityIdentity.builder().setPrincipal(jwtPrincipal)
                        .addRoles(jwtPrincipal.getGroups())
                        .addAttribute(SecurityIdentity.USER_ATTRIBUTE, jwtPrincipal).build());

            } catch (ParseException e) {
                log.debug("Authentication failed", e);
                uniEmitter.fail(new AuthenticationFailedException(e));
            }
        }
    });

}
 
Example #2
Source File: EjbTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TCKConstants.TEST_GROUP_EJB,
    description = "Validate a request with MP-JWT SecurityContext.getUserPrincipal() is a JsonWebToken")
public void testEJBPrincipalClass() throws Exception {
    String uri = baseURL.toExternalForm() + "endp/getEJBPrincipalClass";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        ;
    Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String reply = response.readEntity(String.class);
    String[] ifaces = reply.split(",");
    boolean hasJsonWebToken = false;
    for(String iface : ifaces) {
        hasJsonWebToken |= iface.equals(JsonWebToken.class.getTypeName());
    }
    Assert.assertTrue(hasJsonWebToken, "EJB PrincipalClass has JsonWebToken interface");
}
 
Example #3
Source File: WebIdPrincipal.java    From trellis with Apache License 2.0 6 votes vote down vote up
static String getWebId(final JsonWebToken jwt) {
    if (jwt.containsClaim("webid")) {
        return jwt.getClaim("webid");
    }

    final String subject = jwt.getSubject();
    if (isUrl(subject)) {
        return subject;
    }

    final String issuer = jwt.getIssuer();
    if (isUrl(issuer)) {
        return concat(issuer, subject);
    }

    return null;
}
 
Example #4
Source File: TestTokenRequireSub.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test(groups = TEST_GROUP_JWT, description = "no sub validation")
public void noSubValidation() throws Exception {
    HashMap<String, Long> timeClaims = new HashMap<>();
    String token = TokenUtils.generateTokenString("/TokenSubPath.json", null, timeClaims);
    PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    if (publicKey == null) {
        throw new IllegalStateException("Failed to load /publicKey.pem resource");
    }

    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
    contextInfo.setRequireNamedPrincipal(false);
    JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
    JsonWebToken jwt = factory.parse(token, contextInfo);
    String sub = jwt.getSubject();
    Assert.assertNull(sub);
}
 
Example #5
Source File: JsonWebTokenValidatorTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testValidate() throws Exception {

    final JsonWebTokenValidator validator = JsonWebTokenValidator.builder()
            .publicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlivFI8qB4D0y2jy0CfEqFyy46R0o7S8TKpsx5xbHKoU1VWg6QkQm+ntyIv1p4kE1sPEQO73+HY8+Bzs75XwRTYL1BmR1w8J5hmjVWjc6R2BTBGAYRPFRhor3kpM6ni2SPmNNhurEAHw7TaqszP5eUF/F9+KEBWkwVta+PZ37bwqSE4sCb1soZFrVz/UT/LF4tYpuVYt3YbqToZ3pZOZ9AX2o1GCG3xwOjkc4x0W7ezbQZdC9iftPxVHR8irOijJRRjcPDtA6vPKpzLl6CyYnsIYPd99ltwxTHjr3npfv/3Lw50bAkbT4HeLFxTx4flEoZLKO/g0bAoV2uqBhkA9xnQIDAQAB")
            .build();

    final String claims = "{" +
            "  \"sub\":\"Jane Awesome\"," +
            "  \"iss\":\"https://server.example.com\"," +
            "  \"groups\":[\"manager\",\"user\"]," +
            "  \"exp\":2552047942" +
            "}";
    final String token = Tokens.asToken(claims);

    final JsonWebToken jwt = validator.validate(token);

    assertEquals("Jane Awesome", jwt.getSubject());
    assertEquals("https://server.example.com", jwt.getIssuer());
    assertEquals(2552047942l, jwt.getExpirationTime());
}
 
Example #6
Source File: ValidationConstraintsTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void valid() throws Exception {
    final ValidationConstraints constraints = ValidationConstraints.of(Circle.class);

    final Method red = Circle.class.getMethod("red");


    final JsonWebTokenValidator validator = JsonWebTokenValidator.builder()
            .publicKey(Tokens.getPublicKey())
            .build();

    final String claims = "{" +
            "  \"sub\":\"Jane Awesome\"," +
            "  \"iss\":\"http://foo.bar.com\"," +
            "  \"aud\":[\"bar\",\"user\"]," +
            "  \"groups\":[\"manager\",\"user\"]," +
            "  \"exp\":2552047942" +
            "}";
    final String token = Tokens.asToken(claims);

    final JsonWebToken jwt = validator.validate(token);

    assertViolations(constraints.validate(red, jwt));
}
 
Example #7
Source File: ServletTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@RunAsClient
@Test(groups = TCKConstants.TEST_GROUP_SERVLET,
    description = "Validate a request with MP-JWT SecurityContext.getUserPrincipal() is a JsonWebToken")
public void getServletPrincipalClass() throws Exception {
    String uri = baseURL.toExternalForm() + "ServiceServlet/getPrincipalClass";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        ;
    Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String reply = response.readEntity(String.class);
    String[] ifaces = reply.split(",");
    boolean hasJsonWebToken = false;
    for(String iface : ifaces) {
        hasJsonWebToken |= iface.equals(JsonWebToken.class.getTypeName());
    }
    Assert.assertTrue(hasJsonWebToken, "PrincipalClass has JsonWebToken interface");
}
 
Example #8
Source File: JWTHttpAuthenticationMechanism.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationStatus validateRequest(HttpServletRequest request,
        HttpServletResponse response,
        HttpMessageContext httpMessageContext)
        throws AuthenticationException {

    AbstractBearerTokenExtractor extractor = new BearerTokenExtractor(request, authContextInfo);
    String bearerToken = extractor.getBearerToken();

    if (bearerToken != null) {
        try {
            JsonWebToken jwtPrincipal = jwtParser.parse(bearerToken);
            producer.setJsonWebToken(jwtPrincipal);
            Set<String> groups = jwtPrincipal.getGroups();
            MechanismLogging.log.success();
            return httpMessageContext.notifyContainerAboutLogin(jwtPrincipal, groups);
        } catch (Exception e) {
            MechanismLogging.log.unableToValidateBearerToken(e);
            return httpMessageContext.responseUnauthorized();
        }
    } else {
        MechanismLogging.log.noUsableBearerTokenFound();
        return httpMessageContext.isProtected() ? httpMessageContext.responseUnauthorized()
                : httpMessageContext.doNothing();
    }
}
 
Example #9
Source File: RolesEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/getInjectedPrincipal")
@RolesAllowed("Tester")
public String getInjectedPrincipal(@Context SecurityContext sec) {
    boolean isJsonWebToken = this.jwtPrincipal instanceof JsonWebToken;
    return "isJsonWebToken:" + isJsonWebToken;
}
 
Example #10
Source File: SubjectEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/getSubjectClass")
@RolesAllowed("Tester")
public String getSubjectClass(@Context SecurityContext sec) throws Exception {
    Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
    Set<? extends Principal> principalSet = subject.getPrincipals(JsonWebToken.class);
    if (principalSet.size() > 0) {
        return "subject.getPrincipals(JWTPrincipal.class) ok";
    }
    throw new IllegalStateException("subject.getPrincipals(JWTPrincipal.class) == 0");
}
 
Example #11
Source File: TestTokenClaimTypes.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test(groups = TEST_GROUP_JWT, description = "validate the name comes from the upn claim")
public void validateNameIsPreferredName() throws Exception {
    String token2 = TokenUtils.generateTokenString("/usePreferredName.json");
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
    JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
    JsonWebToken jwt2 = factory.parse(token2, contextInfo);
    Assert.assertEquals("jdoe", jwt2.getName());
}
 
Example #12
Source File: TestTokenWithGroupsPath.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test(groups = TEST_GROUP_JWT, description = "validate the custom groups claim is not available if the claim is not array")
public void groupsClaimIsNotAvailableIfClaimIsNotArray() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
    contextInfo.setGroupsPath("realm/access/groups");
    JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
    JsonWebToken jwt = factory.parse(token, contextInfo);
    Assert.assertTrue(jwt.getGroups().isEmpty());
}
 
Example #13
Source File: OidcJsonWebTokenProducer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private JsonWebToken getTokenCredential(Class<? extends TokenCredential> type) {
    if (identity.isAnonymous()) {
        return new NullJsonWebToken();
    }
    if (identity.getPrincipal() instanceof OidcJwtCallerPrincipal
            && ((OidcJwtCallerPrincipal) identity.getPrincipal()).getCredential().getClass() == type) {
        return (JsonWebToken) identity.getPrincipal();
    }
    TokenCredential credential = identity.getCredential(type);
    if (credential != null) {
        if (credential instanceof AccessTokenCredential && ((AccessTokenCredential) credential).isOpaque()) {
            throw new OIDCException("Opaque access token can not be converted to JsonWebToken");
        }
        JwtClaims jwtClaims;
        try {
            jwtClaims = new JwtConsumerBuilder()
                    .setSkipSignatureVerification()
                    .setSkipAllValidators()
                    .build().processToClaims(credential.getToken());
        } catch (InvalidJwtException e) {
            throw new OIDCException(e);
        }
        jwtClaims.setClaim(Claims.raw_token.name(), credential.getToken());
        return new OidcJwtCallerPrincipal(jwtClaims, credential);
    }
    String tokenType = type == AccessTokenCredential.class ? "access" : "ID";
    throw new OIDCException("Current identity is not associated with an " + tokenType + " token");
}
 
Example #14
Source File: OidcJsonWebTokenProducer.java    From quarkus with Apache License 2.0 5 votes vote down vote up
/**
 * The producer method for the current id token
 *
 * @return the id token
 */
@Produces
@IdToken
@RequestScoped
JsonWebToken currentIdToken() {
    return getTokenCredential(IdTokenCredential.class);
}
 
Example #15
Source File: JwtResource.java    From boost with Eclipse Public License 1.0 5 votes vote down vote up
@GET
@RolesAllowed({ "admin", "user" })
@Path("/groups")
public Response getJwtGroups(@Context SecurityContext securityContext) {
    Set<String> groups = null;
    Principal user = securityContext.getUserPrincipal();
    if (user instanceof JsonWebToken) {
        JsonWebToken jwt = (JsonWebToken) user;
        groups = jwt.getGroups();
    }
    return Response.ok(groups.toString()).build();
}
 
Example #16
Source File: TestTokenRequireSub.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test(groups = TEST_GROUP_JWT, description = "validate sub")
public void defaultSubAvailable() throws Exception {
    HashMap<String, Long> timeClaims = new HashMap<>();
    String token = TokenUtils.generateTokenString("/Token1.json", null, timeClaims);
    PublicKey publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    if (publicKey == null) {
        throw new IllegalStateException("Failed to load /publicKey.pem resource");
    }

    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo((RSAPublicKey) publicKey, TEST_ISSUER);
    JWTCallerPrincipalFactory factory = JWTCallerPrincipalFactory.instance();
    JsonWebToken jwt = factory.parse(token, contextInfo);
    String sub = jwt.getSubject();
    Assert.assertEquals(sub, "24400320");
}
 
Example #17
Source File: PrincipalInjectionEndpoint.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/verifyInjectedPrincipal")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyInjectedPrincipal() {
    boolean pass = false;
    String msg;
    // Validate that the context principal is a JsonWebToken
    Principal jwtPrincipal = context.getUserPrincipal();
    if (jwtPrincipal == null) {
        msg = "SecurityContext#principal value is null, FAIL";
    } else if (jwtPrincipal instanceof JsonWebToken) {
        msg = "SecurityContext#getUserPrincipal is JsonWebToken, PASS";
        pass = true;
    } else {
        msg = String.format("principal: JsonWebToken != %s", jwtPrincipal.getClass().getCanonicalName());
    }
    // Validate that the injection built-in principal name matches the JsonWebToken name
    if (pass) {
        pass = false;
        if (principal == null) {
            msg = "Injected principal value is null, FAIL";
        } else if (!principal.getName().equals(jwtPrincipal.getName())) {
            msg = "Injected principal#name != jwtPrincipal#name, FAIL";
        } else {
            msg += "\nInjected Principal#getName matches, PASS";
            pass = true;
        }
    }

    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example #18
Source File: RolesEndpoint.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Validate that the  SecurityContext#getUserPrincipal is a JsonWebToken
 * @param sec
 * @return
 */
@GET
@Path("/getPrincipalClass")
@RolesAllowed("Tester")
public String getPrincipalClass(@Context SecurityContext sec) {
    Principal user = sec.getUserPrincipal();
    boolean isJsonWebToken = user instanceof JsonWebToken;
    return "isJsonWebToken:"+isJsonWebToken;
}
 
Example #19
Source File: WebIdSecurityContext.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Create a WebID-based security context.
 * @param delegate the security context delegate
 * @param principal the principal
 * @param admins a whitelist of admin users
 */
public WebIdSecurityContext(final SecurityContext delegate, final JsonWebToken principal,
        final Set<String> admins) {
    this.delegate = delegate;
    this.principal = principal != null ? new WebIdPrincipal(principal) : principal;
    this.admins = admins;
}
 
Example #20
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testIssNoSlashPrincipal() {
    final String iss = "http://idp.example.com";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertTrue(principal.getClaimNames().contains("sub"));
    assertEquals(iss + "/" + sub, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example #21
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testWebIdPrincipal() {
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final String webid = "https://example.com/profile#me";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    claims.setClaim("webid", webid);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertEquals(webid, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
    assertEquals(sub, principal.getClaim("sub"));
}
 
Example #22
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testWebIdSubPrincipal() {
    final String iss = "https://example.com/idp/";
    final String webid = "https://example.com/profile#me";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(webid);
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertEquals(webid, principal.getName());
    assertEquals(iss, principal.getIssuer());
    assertEquals(iss, principal.getClaim("iss"));
}
 
Example #23
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testNoIssuerPrincipal() {
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertNull(principal.getName());
}
 
Example #24
Source File: WebIdPrincipalTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testNoSubPrincipal() {
    final String iss = "https://example.com/idp/";
    final JwtClaims claims = new JwtClaims();
    claims.setIssuer(iss);
    final JsonWebToken principal = new WebIdPrincipal(new DefaultJWTCallerPrincipal(claims));
    assertNull(principal.getName());
}
 
Example #25
Source File: WebIdSecurityContextTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testAdminRoles() {
    final SecurityContext mockDelegate = mock(SecurityContext.class);
    final String iss = "https://example.com/idp/";
    final String sub = "acoburn";
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(sub);
    claims.setIssuer(iss);
    final JsonWebToken principal = new DefaultJWTCallerPrincipal(claims);

    final SecurityContext ctx = new WebIdSecurityContext(mockDelegate, principal, singleton(iss + sub));
    assertTrue(ctx.isUserInRole(WebIdSecurityContext.ADMIN_ROLE));
    assertFalse(ctx.isUserInRole("other-role"));
}
 
Example #26
Source File: JsonWebTokenValidator.java    From tomee with Apache License 2.0 5 votes vote down vote up
public JsonWebTokenValidator(final Predicate<JsonWebToken> validation, final Key verificationKey, final String issuer, final Map<String, Key> verificationKeys, final boolean allowNoExpiryClaim) {
    this.validation = validation;
    this.verificationKey = verificationKey;
    this.verificationKeys = verificationKeys;
    this.issuer = issuer;
    this.allowNoExpiryClaim = allowNoExpiryClaim;
}
 
Example #27
Source File: ClaimBean.java    From tomee with Apache License 2.0 5 votes vote down vote up
private T getClaimValue(final String name) {
    final Bean<?> bean = bm.resolve(bm.getBeans(Principal.class));
    final Principal principal = Principal.class.cast(bm.getReference(bean, Principal.class, null));

    if (principal == null) {
        logger.fine(String.format("Can't retrieve claim %s. No active principal.", name));
        return null;
    }

    // TomEE sometimes wraps the principal with a proxy so we may have a non null principal even if we aren't authenticated
    // we could merge this test with previous sanity check, but it would make it less readable
    final boolean isProxy = Proxy.isProxyClass(principal.getClass())
            && ManagedSecurityService.PrincipalInvocationHandler.class.isInstance(Proxy.getInvocationHandler(principal));
    if (isProxy) {
        if (!ManagedSecurityService.PrincipalInvocationHandler.class.cast(Proxy.getInvocationHandler(principal)).isLogged()) {
            logger.fine(String.format("Can't retrieve claim %s. No active principal.", name));
            return null;
        }
    }

    JsonWebToken jsonWebToken = null;
    if (!JsonWebToken.class.isInstance(principal)) {
        logger.fine(String.format("Can't retrieve claim %s. Active principal is not a JWT.", name));
        return null;
    }

    jsonWebToken = JsonWebToken.class.cast(principal);

    final Optional<T> claimValue = jsonWebToken.claim(name);
    logger.finest(String.format("Found ClaimValue=%s for name=%s", claimValue, name));
    return claimValue.orElse(null);
}
 
Example #28
Source File: MPJWTProducer.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Produces
@RequestScoped
public JsonWebToken currentPrincipal() {
    Objects.requireNonNull(httpServletRequest, "HTTP Servlet Request is required to produce a JSonWebToken principal.");

    // not very beautiful, but avoids having the MPJWTFilter setting the request or the principal in a thread local
    // CDI integration already has one - dunno which approach is the best for now
    final Object tokenAttribute = httpServletRequest.getAttribute(JsonWebToken.class.getName());
    if (Function.class.isInstance(tokenAttribute)) {
        return (JsonWebToken) Function.class.cast(tokenAttribute).apply(httpServletRequest);
    }

    return null;
}
 
Example #29
Source File: MPJWTCDIExtension.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void registerClaimProducer(@Observes final AfterBeanDiscovery abd, final BeanManager bm) {

        final Set<Type> types = injectionPoints.stream()
                .filter(NOT_PROVIDERS)
                .filter(NOT_INSTANCES)
                .map(ip -> REPLACED_TYPES.getOrDefault(ip.getType(), ip.getType()))
                .collect(Collectors.<Type>toSet());

        final Set<Type> providerTypes = injectionPoints.stream()
                .filter(NOT_PROVIDERS.negate())
                .map(ip -> ((ParameterizedType) ip.getType()).getActualTypeArguments()[0])
                .collect(Collectors.<Type>toSet());

        final Set<Type> instanceTypes = injectionPoints.stream()
                .filter(NOT_INSTANCES.negate())
                .map(ip -> ((ParameterizedType) ip.getType()).getActualTypeArguments()[0])
                .collect(Collectors.<Type>toSet());

        types.addAll(providerTypes);
        types.addAll(instanceTypes);

        types.stream()
                .map(type -> new ClaimBean<>(bm, type))
                .forEach((Consumer<ClaimBean>) abd::addBean);

        abd.addBean()
                .id(MPJWTCDIExtension.class.getName() + "#" + JsonWebToken.class.getName())
                .beanClass(JsonWebToken.class)
                .types(JsonWebToken.class, Object.class)
                .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
                .scope(Dependent.class)
                .createWith(ctx -> {
                    final Principal principal = getContextualReference(Principal.class, bm);
                    if (JsonWebToken.class.isInstance(principal)) {
                        return JsonWebToken.class.cast(principal);
                    }

                    return null;
                });
    }
 
Example #30
Source File: ValidationConstraintsTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidAudAndIss() throws Exception {
    final ValidationConstraints constraints = ValidationConstraints.of(Circle.class);

    final Method red = Circle.class.getMethod("red");


    final JsonWebTokenValidator validator = JsonWebTokenValidator.builder()
            .publicKey(Tokens.getPublicKey())
            .build();

    final String claims = "{" +
            "  \"sub\":\"Jane Awesome\"," +
            "  \"iss\":\"http://something.com\"," +
            "  \"groups\":[\"manager\",\"user\"]," +
            "  \"exp\":2552047942" +
            "}";
    final String token = Tokens.asToken(claims);

    final JsonWebToken jwt = validator.validate(token);

    assertViolations(constraints.validate(red, jwt),
            "The 'aud' claim is required",
            "The 'aud' claim must contain 'bar'",
            "The 'iss' claim must be 'http://foo.bar.com'"
    );
}