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) 

Source Link

Usage

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

@Override
@Transactional(readOnly = true)//from   w w  w .  j a va2s.  c  o  m
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    log.debug("loadAuthentication accessToken:{}", accessToken);
    AuthorizationGrant authorizationGrant = authorizationGrantRepository.findByAccessToken(accessToken);
    if (authorizationGrant == null) {
        throw new InvalidTokenException("Invalid access token: " + accessToken);
    } else if (hasExpiredAccessToken(authorizationGrant)) {
        throw new InvalidTokenException("Access token expired: " + accessToken);
    } else if (!validateLegalGuardianInAuthrizationGrant(authorizationGrant)) {
        throw new InvalidGrantException(
                "Authorization grant is missing a valid legal guardian: " + accessToken);
    }

    OAuth2Authentication auth = buildAuthenticationFromAuthorizationGrant(authorizationGrant,
            buildScopeFromAuthorizationGrant(authorizationGrant));
    log.debug("returning from loadAuthentication");
    return auth;
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

@Override
@Transactional(readOnly = true)/* w  w w. j  a va2  s .  c o  m*/
public String getClientId(String tokenValue) {
    log.debug("getClientId tokenValue:{}", tokenValue);
    AuthorizationGrant authorizationGrant = authorizationGrantRepository.findByAccessToken(tokenValue);

    if (authorizationGrant == null) {
        throw new InvalidTokenException("Invalid access token: " + tokenValue);
    }

    String clientId = authorizationGrant.getClientId();
    log.debug("Returning from getClientId");
    return clientId;
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

private Map<String, Object> getClaimsForToken(String token) {
    Jwt tokenJwt;//from   www.j a v a2s  .  c om
    try {
        tokenJwt = JwtHelper.decode(token);
    } catch (Throwable t) {
        throw new InvalidTokenException("Invalid token (could not decode): " + token);
    }

    Map<String, Object> claims;
    try {
        claims = JsonUtils.readValue(tokenJwt.getClaims(), new TypeReference<Map<String, Object>>() {
        });
    } catch (Exception e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    String kid = tokenJwt.getHeader().getKid();
    assertNotNull("Token should have a key ID.", kid);
    tokenJwt.verifySignature(KeyInfo.getKey(kid).getVerifier());

    return claims;
}

From source file:org.cloudfoundry.identity.uaa.oauth.CheckTokenEndpoint.java

@RequestMapping(value = "/check_token")
@ResponseBody//w ww  .  java2  s . c o  m
public Claims checkToken(@RequestParam("token") String value,
        @RequestParam(name = "scopes", required = false, defaultValue = "") List<String> scopes) {

    OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
    if (token == null) {
        throw new InvalidTokenException("Token was not recognised");
    }

    if (token.isExpired()) {
        throw new InvalidTokenException("Token has expired");
    }

    try {
        resourceServerTokenServices.loadAuthentication(value);
    } catch (AuthenticationException x) {
        throw new InvalidTokenException((x.getMessage()));
    }

    Claims response = getClaimsForToken(token.getValue());

    List<String> claimScopes = response.getScope().stream().map(String::toLowerCase)
            .collect(Collectors.toList());

    List<String> missingScopes = new ArrayList<>();
    for (String expectedScope : scopes) {
        if (!claimScopes.contains(expectedScope.toLowerCase())) {
            missingScopes.add(expectedScope);
        }
    }

    if (!missingScopes.isEmpty()) {
        throw new InvalidScopeException(
                "Some requested scopes are missing: " + String.join(",", missingScopes));
    }

    return response;
}

From source file:org.cloudfoundry.identity.uaa.oauth.CheckTokenEndpoint.java

private Claims getClaimsForToken(String token) {
    Jwt tokenJwt;/* w w  w. j a va 2 s.com*/
    try {
        tokenJwt = JwtHelper.decode(token);
    } catch (Throwable t) {
        throw new InvalidTokenException("Invalid token (could not decode): " + token);
    }

    Claims claims;
    try {
        claims = JsonUtils.readValue(tokenJwt.getClaims(), Claims.class);
    } catch (JsonUtils.JsonUtilException e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    return claims;
}

From source file:org.cloudfoundry.identity.uaa.oauth.CheckTokenEndpoint.java

@ExceptionHandler(InvalidTokenException.class)
public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
    logger.info("Handling error: " + e.getClass().getSimpleName() + ", " + e.getMessage());
    // This isn't an oauth resource, so we don't want to send an
    // unauthorized code here.
    // The client has already authenticated successfully with basic auth and
    // should just
    // get back the invalid token error.
    InvalidTokenException e400 = new InvalidTokenException(e.getMessage()) {
        @Override/*ww w  .j a v a2 s.  co m*/
        public int getHttpErrorCode() {
            return 400;
        }
    };
    return exceptionTranslator.translate(e400);
}

From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }// w  w  w  . j a v a  2 s  . c o  m

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

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

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.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 : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.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(map, scope);

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

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

@Override
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request)
        throws AuthenticationException {
    if (null == refreshTokenValue) {
        throw new InvalidTokenException("Invalid refresh token (empty token)");
    }//  w  w w  . j  a v a2  s .c  o m

    if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) {
        throw new InvalidGrantException(
                "Invalid grant type: " + request.getRequestParameters().get("grant_type"));
    }

    Map<String, Object> claims = getClaimsForToken(refreshTokenValue);

    // TODO: Should reuse the access token you get after the first
    // successful authentication.
    // You will get an invalid_grant error if your previous token has not
    // expired yet.
    // OAuth2RefreshToken refreshToken =
    // tokenStore.readRefreshToken(refreshTokenValue);
    // if (refreshToken == null) {
    // throw new InvalidGrantException("Invalid refresh token: " +
    // refreshTokenValue);
    // }

    String clientId = (String) claims.get(CID);
    if (clientId == null || !clientId.equals(request.getClientId())) {
        throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
    }

    String userid = (String) claims.get(USER_ID);

    // TODO: Need to add a lookup by id so that the refresh token does not
    // need to contain a name
    UaaUser user = userDatabase.retrieveUserById(userid);

    Integer refreshTokenIssuedAt = (Integer) claims.get(IAT);
    long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l;

    // If the user changed their password, expire the refresh token
    if (user.getModified().after(new Date(refreshTokenIssueDate))) {
        logger.debug("User was last modified at " + user.getModified() + " refresh token was issued at "
                + new Date(refreshTokenIssueDate));
        throw new InvalidTokenException("Invalid refresh token (password changed): " + refreshTokenValue);
    }

    Integer refreshTokenExpiry = (Integer) claims.get(EXP);
    long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l;

    if (new Date(refreshTokenExpireDate).before(new Date())) {
        throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at "
                + new Date(refreshTokenExpireDate));
    }

    @SuppressWarnings("unchecked")
    ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);

    // default request scopes to what is in the refresh token
    Set<String> requestedScopes = request.getScope();
    if (requestedScopes.isEmpty()) {
        requestedScopes = new HashSet<String>(tokenScopes);
    }

    // The user may not request scopes that were not part of the refresh
    // token
    if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) {
        throw new InvalidScopeException(
                "Unable to narrow the scope of the client authentication to " + requestedScopes + ".",
                new HashSet<String>(tokenScopes));
    }

    // from this point on, we only care about the scopes requested, not what
    // is in the refresh token
    // ensure all requested scopes are approved: either automatically or
    // explicitly by the user
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
    String grantType = claims.get(GRANT_TYPE).toString();
    checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client),
            new Date(refreshTokenIssueDate));

    // if we have reached so far, issue an access token
    Integer validity = client.getAccessTokenValiditySeconds();

    @SuppressWarnings("unchecked")
    Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR);

    Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD));

    OAuth2AccessToken accessToken = createAccessToken(user.getId(), user.getUsername(), user.getEmail(),
            validity != null ? validity.intValue() : accessTokenValiditySeconds, null, requestedScopes,
            clientId, audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType,
            refreshTokenValue, additionalAuthorizationInfo, new HashSet<String>()); //TODO populate response types

    return accessToken;
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

private void checkForApproval(String userid, String clientId, Collection<String> requestedScopes,
        Collection<String> autoApprovedScopes, Date updateCutOff) {
    Set<String> approvedScopes = new HashSet<String>();
    approvedScopes.addAll(autoApprovedScopes);

    // Search through the users approvals for scopes that are requested, not
    // auto approved, not expired,
    // not DENIED and not approved more recently than when this access token
    // was issued.
    List<Approval> approvals = approvalStore.getApprovals(userid, clientId);
    for (Approval approval : approvals) {
        if (requestedScopes.contains(approval.getScope()) && approval.getStatus() == ApprovalStatus.APPROVED) {
            if (!approval.isCurrentlyActive()) {
                logger.debug("Approval " + approval + " has expired. Need to re-approve.");
                throw new InvalidTokenException("Invalid token (approvals expired)");
            }//  w  w  w . ja  va 2  s . c  o  m
            if (updateCutOff.before(approval.getLastUpdatedAt())) {
                logger.debug("At least one approval " + approval + " was updated more recently at "
                        + approval.getLastUpdatedAt() + " access token was issued at " + updateCutOff);
                throw new InvalidTokenException(
                        "Invalid token (approvals updated): " + approval.getLastUpdatedAt());
            }
            approvedScopes.add(approval.getScope());
        }
    }

    // Only issue the token if all the requested scopes have unexpired
    // approvals made before the refresh token was
    // issued OR if those scopes are auto approved
    if (!approvedScopes.containsAll(requestedScopes)) {
        logger.debug("All requested scopes " + requestedScopes + " were not approved " + approvedScopes);
        Set<String> unapprovedScopes = new HashSet<String>(requestedScopes);
        unapprovedScopes.removeAll(approvedScopes);
        throw new InvalidTokenException(
                "Invalid token (some requested scopes are not approved): " + unapprovedScopes);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

private OAuth2AccessToken createAccessToken(String userId, String username, String userEmail,
        int validitySeconds, Collection<GrantedAuthority> clientScopes, Set<String> requestedScopes,
        String clientId, Set<String> resourceIds, String grantType, String refreshToken,
        Map<String, String> additionalAuthorizationAttributes, Set<String> responseTypes)
        throws AuthenticationException {
    String tokenId = UUID.randomUUID().toString();
    OpenIdToken accessToken = new OpenIdToken(tokenId);
    if (validitySeconds > 0) {
        accessToken.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    }/*w w w .  j  av  a  2 s  .  c o  m*/
    accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken));

    if (null == requestedScopes || requestedScopes.size() == 0) {
        logger.debug("No scopes were granted");
        throw new InvalidTokenException("No scopes were granted");
    }

    accessToken.setScope(requestedScopes);

    Map<String, Object> info = new HashMap<String, Object>();
    info.put(JTI, accessToken.getValue());
    if (null != additionalAuthorizationAttributes) {
        info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes);
    }
    accessToken.setAdditionalInformation(info);

    String content;
    try {
        content = mapper.writeValueAsString(createJWTAccessToken(accessToken, userId, username, userEmail,
                clientScopes, requestedScopes, clientId, resourceIds, grantType, refreshToken));
    } catch (Exception e) {
        throw new IllegalStateException("Cannot convert access token to JSON", e);
    }
    String token = JwtHelper.encode(content, signerProvider.getSigner()).getEncoded();

    // This setter copies the value and returns. Don't change.
    accessToken.setValue(token);
    populateIdToken(accessToken, requestedScopes, responseTypes);
    publish(new TokenIssuedEvent(accessToken, SecurityContextHolder.getContext().getAuthentication()));

    return accessToken;
}