Example usage for org.springframework.security.oauth2.common.exceptions InvalidTokenException InvalidTokenException

List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidTokenException InvalidTokenException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions InvalidTokenException InvalidTokenException.

Prototype

public InvalidTokenException(String msg, Throwable t) 

Source Link

Usage

From source file:com.netflix.genie.web.security.oauth2.pingfederate.PingFederateJWTTokenServices.java

/**
 * Load the credentials for the specified access token.
 *
 * @param accessToken The access token value.
 * @return The authentication for the access token.
 * @throws AuthenticationException If the access token is expired
 * @throws InvalidTokenException   if the token isn't valid
 *//*from   w  w w . j  av  a 2s. co m*/
@Override
public OAuth2Authentication loadAuthentication(final String accessToken)
        throws AuthenticationException, InvalidTokenException {
    final long start = System.nanoTime();

    try {
        final JwtClaims claims = this.jwtConsumer.processToClaims(accessToken);
        log.debug("Ping Federate JWT Claims: {}", claims);
        return new OAuth2Authentication(this.getOAuth2Request(claims), null);
    } catch (final InvalidJwtException | MalformedClaimException e) {
        throw new InvalidTokenException(e.getMessage(), e);
    } finally {
        this.loadAuthenticationTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.ge.predix.uaa.token.lib.FastTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(final String accessToken) throws AuthenticationException {
    Map<String, Object> claims;
    try {/*from ww  w.j  av a 2s  .co  m*/
        claims = getTokenClaims(accessToken);
    } catch (IllegalArgumentException e) {
        LOG.error("Malformed Access Token: " + accessToken);
        LOG.error(e);
        throw new InvalidTokenException("Malformed Access Token", e);
    }
    String iss = getIssuerFromClaims(claims);

    verifyIssuer(iss);

    // check if the singerProvider for that issuer has already in the cache
    SignatureVerifier verifier = this.tokenKeys.get(iss);
    if (null == verifier) {
        String tokenKey = getTokenKey(iss);
        verifier = getVerifier(tokenKey);
        this.tokenKeys.put(iss, verifier);
    }

    JwtHelper.decodeAndVerify(accessToken, verifier);
    verifyTimeWindow(claims);

    Assert.state(claims.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) claims.get("client_id");

    Set<String> scope = new HashSet<>();
    if (claims.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) claims.get("scope");
        scope.addAll(values);
    }

    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (claims.containsKey("resource_ids") || claims.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<>();
        if (claims.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("resource_ids");
            resourceIds.addAll(values);
        }

        Set<GrantedAuthority> clientAuthorities = new HashSet<>();
        if (claims.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) claims.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }

        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }

    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : claims.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (claims.containsKey(Claims.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(Claims.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(claims.get(Claims.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(claims, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

From source file:org.cloudfoundry.identity.uaa.util.TokenValidation.java

private TokenValidation(String token) {
    this.token = token;

    Jwt tokenJwt;/*from   www . j av a  2  s  .  co  m*/
    try {
        tokenJwt = JwtHelper.decode(token);
    } catch (Exception ex) {
        tokenJwt = null;
        validationErrors.add(new InvalidTokenException("Invalid token (could not decode): " + token, ex));
    }
    this.tokenJwt = tokenJwt;

    String tokenJwtClaims;
    if (tokenJwt != null && StringUtils.hasText(tokenJwtClaims = tokenJwt.getClaims())) {
        Map<String, Object> claims;
        try {
            claims = JsonUtils.readValue(tokenJwtClaims, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonUtils.JsonUtilException ex) {
            claims = null;
            validationErrors
                    .add(new InvalidTokenException("Invalid token (cannot read token claims): " + token, ex));
        }
        this.claims = claims;
    } else {
        this.claims = new HashMap<>();
    }

    this.decoded = isValid();
}

From source file:org.cloudfoundry.identity.uaa.util.TokenValidation.java

private boolean addError(String msg, Exception cause) {
    return validationErrors.add(new InvalidTokenException(msg, cause));
}

From source file:org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator.java

public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

    // Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    RuntimeException ase = (AuthenticationException) throwableAnalyzer
            .getFirstThrowableOfType(AuthenticationException.class, causeChain);

    if (ase instanceof OAuth2Exception) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }/*from   www  . ja  va  2s .  co  m*/

    if (ase instanceof AuthenticationException) {
        return handleOAuth2Exception(new InvalidTokenException(e.getMessage(), e));
    }

    if (ase == null) {
        ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class,
                causeChain);
        if (ase instanceof AccessDeniedException) {
            return handleOAuth2Exception(new WrappedException(ase.getMessage(), ase));
        }
    }

    throw e;

}

From source file:org.springframework.security.oauth2.provider.token.JwtTokenEnhancer.java

protected Map<String, Object> decode(String token) {
    Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
    String content = jwt.getClaims();
    try {/*from   ww w. ja v a  2 s .com*/
        @SuppressWarnings("unchecked")
        Map<String, Object> map = objectMapper.readValue(content, Map.class);
        return map;
    } catch (Exception e) {
        throw new InvalidTokenException("Cannot convert access token to JSON", e);
    }
}

From source file:org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter.java

protected Map<String, Object> decode(String token) {
    try {/*from   w w w  . j  a  va  2  s .  c  o  m*/
        Jwt jwt = JwtHelper.decodeAndVerify(token, verifier);
        String content = jwt.getClaims();
        @SuppressWarnings("unchecked")
        Map<String, Object> map = objectMapper.readValue(content, Map.class);
        return map;
    } catch (Exception e) {
        throw new InvalidTokenException("Cannot convert access token to JSON", e);
    }
}