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

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

Introduction

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

Prototype

public InsufficientScopeException(String msg) 

Source Link

Usage

From source file:org.mitre.uma.service.impl.DefaultPermissionService.java

@Override
public PermissionTicket createTicket(ResourceSet resourceSet, Set<String> scopes) {

    // check to ensure that the scopes requested are a subset of those in the resource set

    if (!scopeService.scopesMatch(resourceSet.getScopes(), scopes)) {
        throw new InsufficientScopeException("Scopes of resource set are not enough for requested permission.");
    }// w  w w  .j  a v a  2 s  .co m

    Permission perm = new Permission();
    perm.setResourceSet(resourceSet);
    perm.setScopes(scopes);

    PermissionTicket ticket = new PermissionTicket();
    ticket.setPermission(perm);
    ticket.setTicket(UUID.randomUUID().toString());
    ticket.setExpiration(new Date(System.currentTimeMillis() + permissionExpirationSeconds * 1000L));

    return repository.save(ticket);

}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ScopeAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (authentication instanceof OAuth2Authentication) {
        AuthorizationRequest creq = ((OAuth2Authentication) authentication).getAuthorizationRequest();
        List<String> scopes = dedup(creq.getScope());
        int matches = 0;
        int requiredMatches = getRequiredScopes().size();
        for (String scope : scopes) {
            if (requiredScopes.contains(scope)) {
                matches++;/* w ww.j  av a  2  s  .c  om*/
            }
        }
        if (matches == requiredMatches) {
            ((DefaultAuthorizationRequest) creq).setApproved(true);
            authentication.setAuthenticated(true);
            return authentication;
        } else if (isThrowOnNotAuthenticated()) {
            throw new InsufficientScopeException("Insufficient scopes");
        }
    } else if (isThrowOnNotAuthenticated()) {
        throw new InvalidTokenException("Missing Oauth 2 authentication.");
    }
    return authentication;
}

From source file:org.cloudfoundry.identity.uaa.oauth.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  . jav  a  2s .c  o m*/

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

    TokenValidation tokenValidation = validateToken(refreshTokenValue);
    Map<String, Object> claims = tokenValidation.getClaims();
    refreshTokenValue = tokenValidation.getJwt().getEncoded();

    @SuppressWarnings("unchecked")
    ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
    if (isRestrictRefreshGrant() && !tokenScopes.contains(UAA_REFRESH_TOKEN)) {
        throw new InsufficientScopeException(String.format("Expected scope %s is missing", UAA_REFRESH_TOKEN));
    }

    // 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);

    String refreshTokenId = (String) claims.get(JTI);
    String accessTokenId = generateUniqueTokenId();

    boolean opaque = TokenConstants.OPAQUE
            .equals(request.getRequestParameters().get(TokenConstants.REQUEST_TOKEN_FORMAT));
    boolean revocable = opaque || (claims.get(REVOCABLE) == null ? false : (Boolean) claims.get(REVOCABLE));

    // 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);
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

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

    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));
    }

    // default request scopes to what is in the refresh token
    Set<String> requestedScopes = request.getScope();
    if (requestedScopes.isEmpty()) {
        requestedScopes = new HashSet<>(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<>(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
    String grantType = claims.get(GRANT_TYPE).toString();
    checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client));

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

    String nonce = (String) claims.get(NONCE);

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

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

    String revocableHashSignature = (String) claims.get(REVOCATION_SIGNATURE);
    if (hasText(revocableHashSignature)) {
        String clientSecretForHash = client.getClientSecret();
        if (clientSecretForHash != null && clientSecretForHash.split(" ").length > 1) {
            clientSecretForHash = clientSecretForHash.split(" ")[1];
        }
        String newRevocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash,
                user);
        if (!revocableHashSignature.equals(newRevocableHashSignature)) {
            throw new TokenRevokedException(refreshTokenValue);
        }
    }

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

    int zoneAccessTokenValidity = getZoneAccessTokenValidity();

    CompositeAccessToken accessToken = createAccessToken(accessTokenId, user.getId(), user,
            (claims.get(AUTH_TIME) != null) ? new Date(((Long) claims.get(AUTH_TIME)) * 1000l) : null,
            validity != null ? validity.intValue() : zoneAccessTokenValidity, null, requestedScopes, clientId,
            audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue,
            nonce, additionalAuthorizationInfo, externalAttributes, new HashSet<>(), revocableHashSignature,
            false, null, //TODO populate response types
            null, revocable, null, null);

    DefaultExpiringOAuth2RefreshToken expiringRefreshToken = new DefaultExpiringOAuth2RefreshToken(
            refreshTokenValue, new Date(refreshTokenExpireDate));
    return persistRevocableToken(accessTokenId, refreshTokenId, accessToken, expiringRefreshToken, clientId,
            user.getId(), opaque, revocable);

}

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

public TokenValidation checkScopesInclude(Collection<String> scopes) {
    getScopes().ifPresent(tokenScopes -> {
        String missingScopes = scopes.stream().filter(s -> !tokenScopes.contains(s))
                .collect(Collectors.joining(" "));
        if (StringUtils.hasText(missingScopes)) {
            validationErrors/*from  ww w.  j a  va2 s  . c o  m*/
                    .add(new InsufficientScopeException("Some expected scopes are missing: " + missingScopes));
        }
    });
    return this;
}