Java Code Examples for com.nimbusds.jwt.SignedJWT#parse()

The following examples show how to use com.nimbusds.jwt.SignedJWT#parse() . 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: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 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 2
Source File: DownstreamPacketHandler.java    From ProxyPass with GNU Affero General Public License v3.0 6 votes vote down vote up
public boolean handle(ServerToClientHandshakePacket packet) {
    try {
        SignedJWT saltJwt = SignedJWT.parse(packet.getJwt());
        URI x5u = saltJwt.getHeader().getX509CertURL();
        ECPublicKey serverKey = EncryptionUtils.generateKey(x5u.toASCIIString());
        SecretKey key = EncryptionUtils.getSecretKey(this.player.getProxyKeyPair().getPrivate(), serverKey,
                Base64.getDecoder().decode(saltJwt.getJWTClaimsSet().getStringClaim("salt")));
        session.enableEncryption(key);
    } catch (ParseException | NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    ClientToServerHandshakePacket clientToServerHandshake = new ClientToServerHandshakePacket();
    session.sendPacketImmediately(clientToServerHandshake);
    return true;
}
 
Example 3
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testValidateTokenSuccessfully() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
}
 
Example 4
Source File: JWTSecurityInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
private boolean verifySignature(String jwt) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(jwt);
        if (new Date().before(signedJWT.getJWTClaimsSet().getExpirationTime())) {
            JWSVerifier verifier =
                    new RSASSAVerifier((RSAPublicKey) getPublicKey(KEYSTORE, KEYSTORE_PASSWORD, ALIAS));
            return signedJWT.verify(verifier);
        } else {
            log.info("Token has expired");
        }
    } catch (ParseException | IOException | KeyStoreException | CertificateException |
            NoSuchAlgorithmException | UnrecoverableKeyException | JOSEException e) {
        log.error("Error occurred while JWT signature verification. JWT=" + jwt, e);
    }
    return false;
}
 
Example 5
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRevalidateTokenPasses() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
  assertTrue(loginService.validate(identity));
}
 
Example 6
Source File: JwtLoginServiceTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRevalidateTokenFails() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[] {"USER"});
  Instant now = Instant.now();
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER, now.plusSeconds(10).toEpochMilli());
  Clock fixedClock = Clock.fixed(now, ZoneOffset.UTC);
  JwtLoginService loginService = new JwtLoginService(
      new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null, fixedClock);

  SignedJWT jwtToken = SignedJWT.parse(tokenAndKeys.token());
  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  replay(request);
  UserIdentity identity = loginService.login(TEST_USER, jwtToken, request);
  verify(request);
  assertNotNull(identity);
  assertEquals(TEST_USER, identity.getUserPrincipal().getName());
  loginService.setClock(Clock.offset(fixedClock, Duration.ofSeconds(20)));
  assertFalse(loginService.validate(identity));
}
 
Example 7
Source File: CustomJWTClaimsInterceptor.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean interceptRequest(Request request, Response response) throws Exception {
    HttpHeaders headers = request.getHeaders();
    if (headers != null) {
        String jwtHeader = headers.getHeaderString(JWT_HEADER);
        if (jwtHeader != null) {
            SignedJWT signedJWT = SignedJWT.parse(jwtHeader);
            ReadOnlyJWTClaimsSet readOnlyJWTClaimsSet = signedJWT.getJWTClaimsSet();
            if (readOnlyJWTClaimsSet != null) {
                // Do something with claims
                return true;
            }
        }
    }
    response.setHeader(javax.ws.rs.core.HttpHeaders.WWW_AUTHENTICATE, AUTH_TYPE_JWT);
    response.setStatus(javax.ws.rs.core.Response.Status.UNAUTHORIZED.getStatusCode());
    return false;
}
 
Example 8
Source File: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> getClaimsFromSignedJWT(TokenValidationContext validationContext) {

        // Get the signed JWT access token
        String accessToken = validationContext.getAccessToken();
        if (Utils.isSignedJWT(accessToken)) {
            try {
                SignedJWT signedJWT = SignedJWT.parse(accessToken);
                return Utils.getCustomClaims(signedJWT);
            } catch (ParseException e) {
                log.error("Error retrieving claims from the JWT Token.", e);
            }
        }

        return Collections.emptyMap();
    }
 
Example 9
Source File: TokenHelperImpl.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public TokenHelperImpl( String token ) throws TokenParseException
{
    try
    {
        this.signedJWT = SignedJWT.parse( token );
        this.token = token;
    }
    catch ( ParseException e )
    {
        throw new TokenParseException( e.getMessage() );
    }
}
 
Example 10
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static boolean validate(JWToken jwToken, String subject, String keyId, X509Certificate certificate) throws ParseException, JOSEException {
    RSASSAVerifier verifier = new RSASSAVerifier((RSAPublicKey)certificate.getPublicKey());
    SignedJWT signedJWT = SignedJWT.parse(jwToken.getToken());
    boolean verified = signedJWT.verify(verifier);
    String sub = signedJWT.getJWTClaimsSet().getSubject();
    String kid = signedJWT.getHeader().getKeyID();
    Date expires = signedJWT.getJWTClaimsSet().getExpirationTime();
    Date nowDate = new Date();
    boolean expired = nowDate.getTime() > expires.getTime();
    return verified && subject.equals(sub) && keyId.equals(kid) && !expired;
}
 
Example 11
Source File: AuthUtils.java    From blog with MIT License 5 votes vote down vote up
public static ReadOnlyJWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {
  SignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));
  if (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) {
    return signedJWT.getJWTClaimsSet();
  } else {
    throw new JOSEException("Signature verification failed");
  }
}
 
Example 12
Source File: AtlasKnoxSSOAuthenticationFilter.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("X-Frame-Options", "DENY");

    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }

    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            //if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                //if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {  // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }

}
 
Example 13
Source File: DefaultConsentReferencePolicy.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("PMD")
private ConsentReference verifyParseJWT(String encryptedConsentId, String authorizationId, String cookieString, boolean strict) {
    Date refTime = new Date();
    try {
        SignedJWT jwt = SignedJWT.parse(cookieString);
        JWTClaimsSet jwtClaimsSet = jwt.getJWTClaimsSet();

        // Validate xsrf
        Object authorizationIdClaim = jwtClaimsSet.getClaim(AUTH_ID_JWT_CLAIM_NAME);
        if (strict && authorizationIdClaim == null) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Missing claim %s for jwt with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        if (authorizationIdClaim != null && !StringUtils.equalsIgnoreCase(authorizationIdClaim.toString(), authorizationId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", AUTH_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        Object encryptedConsentIdClaim = jwtClaimsSet.getClaim(ENC_CONSENT_ID_JWT_CLAIM_NAME);
        if (encryptedConsentIdClaim == null || !StringUtils.equalsIgnoreCase(encryptedConsentIdClaim.toString(), encryptedConsentId)) {
            throw invalidConsent(String.format("Wrong jwt. CSRF allert. Wrong %s for token with redirectId %s", ENC_CONSENT_ID_JWT_CLAIM_NAME, jwtClaimsSet.getClaim(REDIRECT_ID_JWT_CLAIM_NAME)));
        }

        JWSHeader header = jwt.getHeader();
        // CHeck algorithm
        if (!JWSAlgorithm.HS256.equals(header.getAlgorithm())) {
            throw invalidConsent(String.format("Wrong jws algo for token with subject : %s", jwtClaimsSet.getSubject()));
        }

        // CHeck expiration
        if (jwtClaimsSet.getExpirationTime() == null || jwtClaimsSet.getExpirationTime().before(refTime)) {
            throw invalidConsent(String.format(
                "Token with subject %s is expired at %s and reference time is %s : ", jwtClaimsSet.getSubject(),
                jwtClaimsSet.getExpirationTime(), refTime));
        }

        // check signature.
        boolean verified = jwt.verify(new MACVerifier(hmacSecret));
        if (!verified) {
            throw invalidConsent(String.format("Could not verify signature of token with subject %s: ", jwtClaimsSet.getSubject()));
        }

        return consentReference(encryptedConsentId, authorizationId, jwtClaimsSet);

    } catch (ParseException | JOSEException e) {
        // If we can not parse the token, we log the error and return false.
        throw invalidConsent(e.getMessage());
    }
}
 
Example 14
Source File: RefreshTokenGrantTypeHandler.java    From tutorials with MIT License 4 votes vote down vote up
@Override
public JsonObject createAccessToken(String clientId, MultivaluedMap<String, String> params) throws Exception {
    String refreshToken = params.getFirst("refresh_token");
    if (refreshToken == null || "".equals(refreshToken)) {
        throw new WebApplicationException("invalid_grant");
    }

    //Decode refresh token
    SignedJWT signedRefreshToken = SignedJWT.parse(refreshToken);
    JWSVerifier verifier = getJWSVerifier();

    if (!signedRefreshToken.verify(verifier)) {
        throw new WebApplicationException("Invalid refresh token.");
    }
    if (!(new Date().before(signedRefreshToken.getJWTClaimsSet().getExpirationTime()))) {
        throw new WebApplicationException("Refresh token expired.");
    }
    String refreshTokenClientId = signedRefreshToken.getJWTClaimsSet().getStringClaim("client_id");
    if (!clientId.equals(refreshTokenClientId)) {
        throw new WebApplicationException("Invalid client_id.");
    }

    //At this point, the refresh token is valid and not yet expired
    //So create a new access token from it.
    String subject = signedRefreshToken.getJWTClaimsSet().getSubject();
    String approvedScopes = signedRefreshToken.getJWTClaimsSet().getStringClaim("scope");

    String requestedScopes = params.getFirst("scope");
    if (requestedScopes != null && !requestedScopes.isEmpty()) {
        Set<String> rScopes = new HashSet(Arrays.asList(requestedScopes.split(" ")));
        Set<String> aScopes = new HashSet(Arrays.asList(approvedScopes.split(" ")));
        if (!aScopes.containsAll(rScopes)) {
            JsonObject error = Json.createObjectBuilder()
                    .add("error", "Invalid_request")
                    .add("error_description", "Requested scopes should be a subset of the original scopes.")
                    .build();
            Response response = Response.status(Response.Status.BAD_REQUEST).entity(error).build();
            throw new WebApplicationException(response);
        }
    } else {
        requestedScopes = approvedScopes;
    }

    String accessToken = getAccessToken(clientId, subject, requestedScopes);
    return Json.createObjectBuilder()
            .add("token_type", "Bearer")
            .add("access_token", accessToken)
            .add("expires_in", expiresInMin * 60)
            .add("scope", requestedScopes)
            .add("refresh_token", refreshToken)
            .build();
}
 
Example 15
Source File: KnoxJwtRealm.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
public String getName(JWTAuthenticationToken upToken) throws ParseException {
  SignedJWT signed = SignedJWT.parse(upToken.getToken());
  String userName = signed.getJWTClaimsSet().getSubject();
  return userName;
}
 
Example 16
Source File: AtlasKnoxSSOAuthenticationFilter.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    HeadersUtil.setHeaderMapAttributes(responseWrapper, HeadersUtil.X_FRAME_OPTIONS_KEY);
    HeadersUtil.setHeaderMapAttributes(responseWrapper, HeadersUtil.X_CONTENT_TYPE_OPTIONS_KEY);
    HeadersUtil.setHeaderMapAttributes(responseWrapper, HeadersUtil.X_XSS_PROTECTION_KEY);
    HeadersUtil.setHeaderMapAttributes(responseWrapper, HeadersUtil.STRICT_TRANSPORT_SEC_KEY);

    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }

    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            //if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                //if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }

                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {  // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }

}
 
Example 17
Source File: KnoxSSOAuthenticationFilter.java    From metron with Apache License 2.0 4 votes vote down vote up
protected SignedJWT parseJWT(String serializedJWT) throws ParseException {
  return SignedJWT.parse(serializedJWT);
}
 
Example 18
Source File: SecurityConfig.java    From oauth2-client with MIT License 4 votes vote down vote up
/**
 * 从access_token中直接抽取角色等信息
 * https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#oauth2login-advanced-map-authorities-oauth2userservice
 *
 * @return
 */
@SuppressWarnings("unchecked")
@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {

    return (userRequest) -> {
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (!StringUtils.hasText(userNameAttributeName)) {
            userNameAttributeName = "sub";
        }
        OAuth2AccessToken accessToken = userRequest.getAccessToken();
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        try {
            SignedJWT jwt = SignedJWT.parse(accessToken.getTokenValue());
            String claimJsonString = jwt.getJWTClaimsSet().toJSONObject().toJSONString();
            Object document = com.jayway.jsonpath.Configuration.defaultConfiguration().jsonProvider().parse(claimJsonString);

            List<Object> authorities = JsonPath.using(conf).parse(document).read("$..roles");

            if (authorities == null || authorities.size() == 0) {
                authorities = JsonPath.using(conf).parse(document).read("$..authorities");
            }
            Collection<String> roles = new ArrayList<>();
            authorities.forEach(authorityItem -> {
                if (authorityItem instanceof String) {
                    roles.add((String) authorityItem);
                } else if (authorityItem instanceof JSONArray) {
                    roles.addAll((Collection<String>) authorityItem);
                } else if (authorityItem instanceof Collection) {
                    roles.addAll((Collection<String>) authorityItem);
                }
            });

            for (String authority : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority));
            }
            Map<String, Object> userAttributes = new HashMap<>(16);
            userAttributes.put(userNameAttributeName, JsonPath.using(conf).parse(document).read("$." + userNameAttributeName));
            userAttributes.put("preferred_username", JsonPath.using(conf).parse(document).read("$.preferred_username"));
            userAttributes.put("email", JsonPath.using(conf).parse(document).read("$.email"));
            OAuth2User oAuth2User = new DefaultOAuth2User(grantedAuthorities, userAttributes, userNameAttributeName);

            return oAuth2User;
        } catch (Exception e) {
            log.error("oauth2UserService Exception", e);
        }
        return null;
    };
}
 
Example 19
Source File: LoginActivity.java    From PoyntSamples with MIT License 4 votes vote down vote up
private void displayAccessTokenInfo(String accessToken) {
    try {
        SignedJWT signedJWT = SignedJWT.parse(accessToken);

        StringBuilder claimsBuffer = new StringBuilder();
        ReadOnlyJWTClaimsSet claims = signedJWT.getJWTClaimsSet();

        claimsBuffer.append("Subject: " + claims.getSubject())
                .append("\nType: " + claims.getType())
                .append("\nIssuer: " + claims.getIssuer())
                .append("\nJWT ID: " + claims.getJWTID())
                .append("\nIssueTime : " + claims.getIssueTime())
                .append("\nExpiration Time: " + claims.getExpirationTime())
                .append("\nNot Before Time: " + claims.getNotBeforeTime());
        for (String audience : claims.getAudience()) {
            claimsBuffer.append("\nAudience: " + audience);
        }

        Map<String, Object> customClaims = claims.getCustomClaims();
        for (Map.Entry<String, Object> entry : customClaims.entrySet()) {
            String key = entry.getKey();
            switch (key) {
                case "poynt.did":
                    key += " (Device ID)";
                    break;
                case "poynt.biz":
                    key += " (Business ID)";
                    break;
                case "poynt.ist":
                    key += " (Issued To)";
                    break;
                case "poynt.sct":
                    key += " (Subject Credential Type [J=JWT, E=EMAIL, U=USERNAME])";
                    break;
                case "poynt.str":
                    key += " (Store ID)";
                    break;
                case "poynt.kid":
                    key += " (Key ID)";
                    break;
                case "poynt.ure":
                    key += " (User Role [O=Owner, E=Employee])";
                    break;
                case "poynt.uid":
                    key += " (Poynt User ID)";
                    break;
                case "poynt.scv":
                    key += " (Subject Credential Value)";
                    break;
                default:
                    break;
            }

            claimsBuffer.append("\n" + key + ": " + entry.getValue());
        }
        final String claimsStr = claimsBuffer.toString();
        Log.d(TAG, "claims: " + claimsStr);
        consoleText.setText(claimsStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
 
Example 20
Source File: JWTValidatorTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void testJWTValidatorExpiredInCacheTenant() throws ParseException, APISecurityException,
        APIManagementException,
        IOException {

    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    SignedJWT signedJWT =
            SignedJWT.parse("eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5UZG1aak00WkRrM05qWTBZemM1T" +
                    "W1abU9EZ3dNVEUzTVdZd05ERTVNV1JsWkRnNE56YzRaQT09In0" +
                    ".eyJhdWQiOiJodHRwOlwvXC9vcmcud3NvMi5hcGltZ3RcL2dhdGV" +
                    "3YXkiLCJzdWIiOiJhZG1pbkBjYXJib24uc3VwZXIiLCJhcHBsaWNhdGlvbiI6eyJvd25lciI6ImFkbWluIiwidGllclF1b3RhVHlwZ" +
                    "SI6InJlcXVlc3RDb3VudCIsInRpZXIiOiJVbmxpbWl0ZWQiLCJuYW1lIjoiRGVmYXVsdEFwcGxpY2F0aW9uIiwiaWQiOjEsInV1aWQ" +
                    "iOm51bGx9LCJzY29wZSI6ImFtX2FwcGxpY2F0aW9uX3Njb3BlIGRlZmF1bHQiLCJpc3MiOiJodHRwczpcL1wvbG9jYWxob3N0Ojk0" +
                    "NDNcL29hdXRoMlwvdG9rZW4iLCJ0aWVySW5mbyI6e30sImtleXR5cGUiOiJQUk9EVUNUSU9OIiwic3Vic2NyaWJlZEFQSXMiOltdL" +
                    "CJjb25zdW1lcktleSI6IlhnTzM5NklIRks3ZUZZeWRycVFlNEhLR3oxa2EiLCJleHAiOjE1OTAzNDIzMTMsImlhdCI6MTU5MDMzO" +
                    "DcxMywianRpIjoiYjg5Mzg3NjgtMjNmZC00ZGVjLThiNzAtYmVkNDVlYjdjMzNkIn0" +
                    ".sBgeoqJn0log5EZflj_G7ADvm6B3KQ9bdfF" +
                    "CEFVQS1U3oY9" +
                    "-cqPwAPyOLLh95pdfjYjakkf1UtjPZjeIupwXnzg0SffIc704RoVlZocAx9Ns2XihjU6Imx2MbXq9ARmQxQkyGVkJ" +
                    "UMTwZ8" +
                    "-SfOnprfrhX2cMQQS8m2Lp7hcsvWFRGKxAKIeyUrbY4ihRIA5vOUrMBWYUx9Di1N7qdKA4S3e8O4KQX2VaZPBzN594c9TG" +
                    "riiH8AuuqnrftfvidSnlRLaFJmko8-QZo8jDepwacaFhtcaPVVJFG4uYP-_" +
                    "-N6sqfxLw3haazPN0_xU0T1zJLPRLC5HPfZMJDMGp" +
                    "EuSe9w");
    JWTConfigurationDto jwtConfigurationDto = new JWTConfigurationDto();
    JWTValidationService jwtValidationService = Mockito.mock(JWTValidationService.class);
    APIKeyValidator apiKeyValidator = Mockito.mock(APIKeyValidator.class);
    Cache gatewayTokenCache = Mockito.mock(Cache.class);
    Cache invalidTokenCache = Mockito.mock(Cache.class);
    Cache gatewayKeyCache = Mockito.mock(Cache.class);
    Cache gatewayJWTTokenCache = Mockito.mock(Cache.class);
    JWTValidationInfo jwtValidationInfo = new JWTValidationInfo();
    jwtValidationInfo.setValid(true);
    jwtValidationInfo.setIssuer("https://localhost");
    jwtValidationInfo.setRawPayload(signedJWT.getParsedString());
    jwtValidationInfo.setJti(UUID.randomUUID().toString());
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis());
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis() + 5L);
    jwtValidationInfo.setConsumerKey(UUID.randomUUID().toString());
    jwtValidationInfo.setUser("user1");
    jwtValidationInfo.setKeyManager("Default");
    Mockito.when(jwtValidationService.validateJWTToken(signedJWT)).thenReturn(jwtValidationInfo);
    JWTValidatorWrapper jwtValidator
            = new JWTValidatorWrapper("Unlimited", true, apiKeyValidator, false, null, jwtConfigurationDto,
            jwtValidationService, invalidTokenCache, gatewayTokenCache, gatewayKeyCache, gatewayJWTTokenCache);
    MessageContext messageContext = Mockito.mock(Axis2MessageContext.class);
    org.apache.axis2.context.MessageContext axis2MsgCntxt =
            Mockito.mock(org.apache.axis2.context.MessageContext.class);
    Mockito.when(axis2MsgCntxt.getProperty(Constants.Configuration.HTTP_METHOD)).thenReturn("GET");
    Map<String, String> headers = new HashMap<>();
    Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS))
            .thenReturn(headers);
    Mockito.when(((Axis2MessageContext) messageContext).getAxis2MessageContext()).thenReturn(axis2MsgCntxt);
    Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/api1");
    Mockito.when(messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION)).thenReturn("1.0");
    Mockito.when(messageContext.getProperty(APIConstants.API_ELECTED_RESOURCE)).thenReturn("/pet/findByStatus");
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_AUTHENTICATION_SUBSCRIPTION_VALIDATION))
            .thenReturn("true");
    jwtValidator.setApiManagerConfiguration(apiManagerConfiguration);
    OpenAPIParser parser = new OpenAPIParser();
    String swagger = IOUtils.toString(this.getClass().getResourceAsStream("/swaggerEntry/openapi.json"));
    OpenAPI openAPI = parser.readContents(swagger, null, null).getOpenAPI();
    APIKeyValidationInfoDTO apiKeyValidationInfoDTO = new APIKeyValidationInfoDTO();
    apiKeyValidationInfoDTO.setApiName("api1");
    apiKeyValidationInfoDTO.setApiPublisher("admin");
    apiKeyValidationInfoDTO.setApiTier("Unlimited");
    apiKeyValidationInfoDTO.setAuthorized(true);
    Mockito.when(apiKeyValidator.validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
            Mockito.anyString(), Mockito.anyString())).thenReturn(apiKeyValidationInfoDTO);
    AuthenticationContext authenticate = jwtValidator.authenticate(signedJWT, messageContext, openAPI);
    Mockito.verify(apiKeyValidator, Mockito.only())
            .validateSubscription(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(),
                    Mockito.anyString(), Mockito.anyString());
    Assert.assertNotNull(authenticate);
    Assert.assertEquals(authenticate.getApiName(), "api1");
    Assert.assertEquals(authenticate.getApiPublisher(), "admin");
    Assert.assertEquals(authenticate.getConsumerKey(), jwtValidationInfo.getConsumerKey());
    Mockito.when(gatewayTokenCache.get(signedJWT.getSignature().toString())).thenReturn("abc.com");
    String cacheKey = GatewayUtils
            .getAccessTokenCacheKey(signedJWT.getSignature().toString(), "/api1", "1.0", "/pet/findByStatus",
                    "GET");
    jwtValidationInfo.setIssuedTime(System.currentTimeMillis() - 100);
    jwtValidationInfo.setExpiryTime(System.currentTimeMillis());
    Mockito.when(gatewayKeyCache.get(cacheKey)).thenReturn(jwtValidationInfo);
    try {
        authenticate = jwtValidator.authenticate(signedJWT, messageContext, openAPI);

    } catch (APISecurityException e) {
        Assert.assertEquals(e.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
    }
    Mockito.verify(jwtValidationService, Mockito.only()).validateJWTToken(signedJWT);
    Mockito.verify(gatewayTokenCache, Mockito.atLeast(2)).get(signedJWT.getSignature().toString());
    Mockito.verify(invalidTokenCache, Mockito.times(1)).put(signedJWT.getSignature().toString(), "abc.com");
}