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

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

Introduction

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

Prototype

public InvalidGrantException(String msg) 

Source Link

Usage

From source file:org.joyrest.oauth2.endpoint.TokenEndpoint.java

@Override
protected void configure() {
    setControllerPath("oauth");

    post("token", (req, resp) -> {
        Authentication principal = basicAuthenticator.authenticate(req);

        String clientId = getClientId(principal);
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

        Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
        TokenRequest tokenRequest = requestFactory.createTokenRequest(parameters, authenticatedClient);

        // Only validate the client details if a client authenticated during this request.
        if (!isEmpty(clientId) && !clientId.equals(tokenRequest.getClientId())) {
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }//from   w ww . j a va2  s  .co  m

        if (nonNull(authenticatedClient)) {
            requestValidator.validateScope(tokenRequest, authenticatedClient);
        }

        if (!isEmpty(tokenRequest.getGrantType())) {
            throw new InvalidRequestException("Missing grant type");
        }

        if (tokenRequest.getGrantType().equals("implicit")) {
            throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
        }

        // The scope was requested or determined during the authorization step
        if (isAuthCodeRequest(parameters) && nonEmpty(tokenRequest.getScope())) {
            tokenRequest.setScope(emptySet());
        }

        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        if (isRefreshTokenRequest(parameters)) {
            tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
        }

        OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
        if (isNull(token)) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }

        createResponse(resp, token);

    }, Resp(OAuth2AccessToken.class)).produces(JSON);
}

From source file:org.energyos.espi.datacustodian.oauth.EspiTokenEnhancer.java

@Transactional(rollbackFor = { javax.xml.bind.JAXBException.class }, noRollbackFor = {
        javax.persistence.NoResultException.class,
        org.springframework.dao.EmptyResultDataAccessException.class })
@Override//from www .  ja va  2 s.  c o m
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

    DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);

    System.out.printf("EspiTokenEnhancer: OAuth2Request Parameters = %s\n",
            authentication.getOAuth2Request().getRequestParameters());

    System.out.printf("EspiTokenEnhancer: Authorities = %s\n", authentication.getAuthorities());

    String clientId = authentication.getOAuth2Request().getClientId();
    ApplicationInformation ai = null;

    // [mjb20150102] Allow REGISTRATION_xxxx and ADMIN_xxxx to use same
    // ApplicationInformation record
    String ci = clientId;
    String clientCredentialsScope = accessToken.getScope().toString();
    if (ci.indexOf("REGISTRATION_") != -1) {
        if (ci.substring(0, "REGISTRATION_".length()).equals("REGISTRATION_")) {
            ci = ci.substring("REGISTRATION_".length());
        }
    }
    if (ci.indexOf("_admin") != -1) {
        ci = ci.substring(0, ci.indexOf("_admin"));
    }

    // Confirm Application Information record exists for ClientID requesting
    // an access token
    try {
        ai = applicationInformationService.findByClientId(ci);

    } catch (NoResultException | EmptyResultDataAccessException e) {
        System.out.printf(
                "\nEspiTokenEnhancer: ApplicationInformation record not found!\n"
                        + "OAuth2Request Parameters = %s\n",
                authentication.getOAuth2Request().getRequestParameters() + " client_id = " + clientId);
        throw new AccessDeniedException(String.format("No client with requested id: %s", clientId));
    }

    Map<String, String> requestParameters = authentication.getOAuth2Request().getRequestParameters();
    String grantType = requestParameters.get(OAuth2Utils.GRANT_TYPE);
    grantType = grantType.toLowerCase();

    // Is this a "client_credentials" access token grant_type request?
    if (grantType.contentEquals("client_credentials")) {
        // Processing a "client_credentials" access token grant_type
        // request.

        // Reject a client_credentials request if Authority equals
        // "ROLE_USER"
        if (authentication.getAuthorities().toString().contains("[ROLE_USER]")) {
            throw new InvalidGrantException(String.format("Client Credentials not valid for ROLE_USER\n"));
        }

        // Create Authorization and add authorizationURI to /oath/token
        // response
        Authorization authorization = authorizationService.createAuthorization(null, result.getValue());
        result.getAdditionalInformation().put("authorizationURI",
                ai.getDataCustodianResourceEndpoint()
                        + Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
                                .replace("{authorizationId}", authorization.getId().toString()));

        // Create Subscription
        Subscription subscription = subscriptionService.createSubscription(authentication);

        // Initialize Authorization record
        authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
        authorization.setAccessToken(accessToken.getValue());
        authorization.setTokenType(accessToken.getTokenType());
        authorization.setExpiresIn((long) accessToken.getExpiresIn());
        authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
        authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));

        if (accessToken.getRefreshToken() != null) {
            authorization.setRefreshToken(accessToken.getRefreshToken().toString());
        }

        // Remove "[" and "]" surrounding Scope in accessToken structure
        authorization.setScope(accessToken.getScope().toString().substring(1,
                (accessToken.getScope().toString().length() - 1)));

        // set the authorizationUri
        authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
                + Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
                        .replace("{authorizationId}", authorization.getId().toString()));

        // Determine resourceURI value based on Client's Role
        Set<String> role = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        if (role.contains("ROLE_DC_ADMIN")) {
            authorization.setResourceURI(ai.getDataCustodianResourceEndpoint() + "/");

        } else {
            if (role.contains("ROLE_TP_ADMIN")) {
                authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
                        + Routes.BATCH_BULK_MEMBER.replace("espi/1_1/resource/", "").replace("{bulkId}", "**"));

            } else {
                if (role.contains("ROLE_UL_ADMIN")) {
                    authorization
                            .setResourceURI(ai.getDataCustodianResourceEndpoint() + Routes.BATCH_UPLOAD_MY_DATA
                                    .replace("espi/1_1/resource/", "").replace("{retailCustomerId}", "**"));
                } else {
                    if (role.contains("ROLE_TP_REGISTRATION")) {
                        authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
                                + Routes.ROOT_APPLICATION_INFORMATION_MEMBER.replace("espi/1_1/resource/", "")
                                        .replace("{applicationInformationId}", ai.getId().toString()));
                    }
                }
            }
        }

        authorization.setApplicationInformation(applicationInformationService.findByClientId(ci));
        authorization.setRetailCustomer(retailCustomerService.findById((long) 0));
        authorization.setUpdated(new GregorianCalendar());
        authorization.setStatus("1"); // Set authorization record status as
        // "Active"
        authorization.setSubscription(subscription);
        authorizationService.merge(authorization);

        // Add resourceURI to access_token response
        result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());

        // Initialize Subscription record
        subscription.setAuthorization(authorization);
        subscription.setUpdated(new GregorianCalendar());
        subscriptionService.merge(subscription);

    } else if (grantType.contentEquals("authorization_code")) {

        try {
            // Is this a refresh_token grant_type request?
            Authorization authorization = authorizationService
                    .findByRefreshToken(result.getRefreshToken().getValue());

            // Yes, update access token
            authorization.setAccessToken(accessToken.getValue());
            authorizationService.merge(authorization);

            // Add ResourceURI and AuthorizationURI to access_token response
            result.getAdditionalInformation().put("resourceURI", authorization.getResourceURI());
            result.getAdditionalInformation().put("authorizationURI", authorization.getAuthorizationURI());

        } catch (NoResultException | EmptyResultDataAccessException e) {
            // No, process as initial access token request

            // Create Subscription and add resourceURI to /oath/token
            // response
            Subscription subscription = subscriptionService.createSubscription(authentication);
            result.getAdditionalInformation().put("resourceURI",
                    ai.getDataCustodianResourceEndpoint()
                            + Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "")
                                    .replace("{subscriptionId}", subscription.getId().toString()));

            // Create Authorization and add authorizationURI to /oath/token
            // response
            Authorization authorization = authorizationService.createAuthorization(subscription,
                    result.getValue());
            result.getAdditionalInformation().put("authorizationURI",
                    ai.getDataCustodianResourceEndpoint()
                            + Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
                                    .replace("{authorizationId}", authorization.getId().toString()));

            // Update Data Custodian subscription structure
            subscription.setAuthorization(authorization);
            subscription.setUpdated(new GregorianCalendar());
            subscriptionService.merge(subscription);

            RetailCustomer retailCustomer = (RetailCustomer) authentication.getPrincipal();

            // link in the usage points associated with this subscription
            List<Long> usagePointIds = resourceService.findAllIdsByXPath(retailCustomer.getId(),
                    UsagePoint.class);
            Iterator<Long> it = usagePointIds.iterator();

            while (it.hasNext()) {
                UsagePoint up = resourceService.findById(it.next(), UsagePoint.class);
                up.setSubscription(subscription);
                resourceService.persist(up); // maybe not needed??
            }

            // Update Data Custodian authorization structure
            authorization.setApplicationInformation(applicationInformationService
                    .findByClientId(authentication.getOAuth2Request().getClientId()));
            authorization.setThirdParty(authentication.getOAuth2Request().getClientId());
            authorization.setRetailCustomer(retailCustomer);
            authorization.setAccessToken(accessToken.getValue());
            authorization.setTokenType(accessToken.getTokenType());
            authorization.setExpiresIn((long) accessToken.getExpiresIn());

            if (accessToken.getRefreshToken() != null) {
                authorization.setRefreshToken(accessToken.getRefreshToken().toString());
            }

            // Remove "[" and "]" surrounding Scope in accessToken structure
            authorization.setScope(accessToken.getScope().toString().substring(1,
                    (accessToken.getScope().toString().length() - 1)));
            authorization.setAuthorizationURI(ai.getDataCustodianResourceEndpoint()
                    + Routes.DATA_CUSTODIAN_AUTHORIZATION.replace("espi/1_1/resource/", "")
                            .replace("{authorizationId}", authorization.getId().toString()));
            authorization.setResourceURI(ai.getDataCustodianResourceEndpoint()
                    + Routes.BATCH_SUBSCRIPTION.replace("espi/1_1/resource/", "").replace("{subscriptionId}",
                            subscription.getId().toString()));
            authorization.setUpdated(new GregorianCalendar());
            authorization.setStatus("1"); // Set authorization record status
            // as "Active"
            authorization.setSubscription(subscription);
            authorization.setAuthorizedPeriod(new DateTimeInterval((long) 0, (long) 0));
            authorization.setPublishedPeriod(new DateTimeInterval((long) 0, (long) 0));

            authorizationService.merge(authorization);
        }

    } else {

        System.out.printf(
                "EspiTokenEnhancer: Invalid Grant_Type processed by Spring Security OAuth2 Framework:\n"
                        + "OAuth2Request Parameters = %s\n",
                authentication.getOAuth2Request().getRequestParameters());
        throw new AccessDeniedException(String.format("Unsupported ESPI OAuth2 grant_type"));
    }

    return result;
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@GetMapping(value = "/v2/idp/login")
public ResponseEntity login(@RequestParam(value = "redirectUrl", required = false) String redirectUrl) {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }// ww  w. j a va  2  s. c  o  m

    if (redirectUrl == null) {
        redirectUrl = idpDefaultRedirectUrl;
    }

    if (redirectUrl == null) {
        log.debug("IDP defaultRedirectUrl is not set. Client did not provide redirectUrl parameter");

        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(new OAuth2Exception("Client did not provide redirectUrl parameter"));
    }

    return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(getIdpLoginUrl(redirectUrl))).build();
}

From source file:org.osiam.security.helper.LessStrictRedirectUriAuthorizationCodeTokenGranter.java

private AuthorizationRequestHolder getAuthorizationRequestHolder(Map<String, String> parameters) {
    String authorizationCode = parameters.get("code");
    if (authorizationCode == null) {
        throw new OAuth2Exception("An authorization code must be supplied.");
    }/* ww  w .  j av  a  2s  . c  o m*/

    AuthorizationRequestHolder storedAuth = authorizationCodeServices
            .consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }
    return storedAuth;
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@GetMapping(value = "/v2/idp/status")
public ResponseEntity status() {
    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }//from w  w w.  j av  a  2 s.c  o  m

    return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(getIdpStatusUrl())).build();
}

From source file:com.companyname.filters.Oauth2ReAuthenticationFilter.java

private Authentication getAuthenticationFromRefreshToken(String _refreshTokenValue) {
    logger.info("obtaining authentication object via refresh token");
    if (_refreshTokenValue == null) {
        return null;
    }// w w  w .  ja  v  a  2s  . c  o m

    OAuth2RefreshToken refreshToken = getTokenStore().readRefreshToken(_refreshTokenValue);
    if (refreshToken == null) {
        throw new InvalidGrantException("Invalid refresh token: " + _refreshTokenValue);
    }

    return getTokenStore().readAuthenticationForRefreshToken(refreshToken);
}

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

@Override
@Transactional(propagation = Propagation.REQUIRED)
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, AuthorizationRequest request)
        throws AuthenticationException {
    log.debug("refreshAccessToken(refreshTokenValue:{}, request:{})", refreshTokenValue, request);

    if (!supportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/*w  w w .ja  va 2  s .c o m*/
    AuthorizationGrant authorizationGrant = authorizationGrantRepository.findByRefreshToken(refreshTokenValue);
    if (authorizationGrant == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }

    if (!validateLegalGuardianInAuthrizationGrant(authorizationGrant)) {
        throw new InvalidGrantException(
                "Authorization grant is missing a valid legal guardian: " + refreshTokenValue);
    }

    OAuth2AccessToken accessToken = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false);
    ExpiringOAuth2RefreshToken refreshToken = (ExpiringOAuth2RefreshToken) accessToken.getRefreshToken();

    if (accessToken == null || accessToken.getRefreshToken() == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }

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

    if (isExpired(accessToken.getRefreshToken())) {
        log.info("Removing expired authorization grant with auth key {} for client {}",
                authorizationGrant.getAuthenticationKey(), authorizationGrant.getClientId());
        authorizationGrantRepository.delete(authorizationGrant);
        throw new InvalidGrantException("Invalid refresh token: " + accessToken.getRefreshToken());
    }

    Set<String> scope = request.getScope();
    // if scope exists, we want to narrow the scope and therefore check that scope is a subset of the original scope
    // else if the scope param is empty, use the old scope from db.
    if (scope != null && scope.size() > 0) {
        if (accessToken.getScope() == null || !accessToken.getScope().containsAll(scope)) {
            throw new InvalidScopeException(
                    "Unable to narrow the scope of the client authentication to " + scope + ".",
                    accessToken.getScope());
        } else if (accessToken.getScope().size() > scope.size()) {

            // if scope is narrowed, check for already existing accesstoken
            OAuth2Authentication auth = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope);
            AuthorizationGrant grant = authorizationGrantRepository
                    .findByAuthenticationKey(authenticationKeyGenerator.extractKey(auth));

            log.info("grant: {}", grant);

            if (grant != null) {
                throw new InvalidScopeException(
                        "Unable to narrow the scope of the client authentication to " + scope
                                + ". An authorization with that scope, client and user already exists.",
                        accessToken.getScope());
            }
        }
    } else {
        scope = accessToken.getScope();
    }

    OAuth2Authentication authentication = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope);

    if (!reuseRefreshToken) {
        refreshToken = buildRefreshToken(authentication);
        authorizationGrant.setRefreshToken(refreshToken.getValue());
        authorizationGrant.setGrantExpires(refreshToken.getExpiration());
    }
    authorizationGrant = buildAuthorizationGrant(authorizationGrant, refreshToken, authentication);
    authorizationGrant = authorizationGrantRepository.save(authorizationGrant);
    OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false);
    log.debug("Returning from refreshAccessToken");
    return token;
}

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

@Override
@Transactional(propagation = Propagation.REQUIRED)
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    log.debug("getAccessToken(authentication:{})", authentication);
    AuthorizationGrant grant = authorizationGrantRepository
            .findByAuthenticationKey(authenticationKeyGenerator.extractKey(authentication));

    if (grant == null) {
        throw new InvalidGrantException("No access token found for authentication");
    }//from  w  w  w. j  av  a2  s . c o m

    OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(grant, true);
    log.debug("returning from getAccessToken");
    return token;
}

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

@Override
@Transactional(readOnly = true)//w w w.  j  a v  a  2 s  . 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;
}