Example usage for org.springframework.security.oauth2.common OAuth2AccessToken getScope

List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getScope

Introduction

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

Prototype

Set<String> getScope();

Source Link

Usage

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

@Test
@DirtiesContext//  w  w w.j  av  a2 s. com
public void testBuildAccessTokenFromAuthorizationGrant() {
    AuthorizationGrant authorizationGrant = buildAuthorizationGrant();

    TokenServicesImpl tokenServices = new TokenServicesImpl();
    tokenServices.setSupportRefreshToken(true);
    OAuth2AccessToken accessToken = tokenServices.buildAccessTokenFromAuthorizationGrant(authorizationGrant,
            true);
    Assert.assertNotNull(accessToken);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    Assert.assertEquals("201205021630", sdf.format(accessToken.getExpiration()));
    Assert.assertEquals("XYZ", accessToken.getRefreshToken().getValue());
    Set<String> scope = accessToken.getScope();
    Assert.assertEquals(2, scope.size());
    Set<String> expectedScopes = new HashSet<String>(Arrays.asList(READ_SCOPE, WRITE_SCOPE));
    for (String actualScope : scope) {
        Assert.assertTrue(expectedScopes.remove(actualScope));
    }
    Assert.assertEquals(OAuth2AccessToken.BEARER_TYPE, accessToken.getTokenType());
    Assert.assertEquals("ABC", accessToken.getValue());
}

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/*w w w.j  a  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:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {

    Map<String, Object> vars = new LinkedHashMap<>();
    Map<String, String> keys = new HashMap<>();

    if (isNull(accessToken)) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }/*from  w w w.j  av  a 2  s.  c om*/

    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();

    if (nonNull(state)) {
        vars.put("state", state);
    }

    Date expiration = accessToken.getExpiration();
    if (nonNull(expiration)) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (isNull(originalScope)
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (nonNull(value)) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}

From source file:com.acc.conv.Oauth2AccessTokenConverter.java

@Override
public void marshal(final Object source, final HierarchicalStreamWriter writerOrig,
        final MarshallingContext context) {
    final OAuth2AccessToken token = (OAuth2AccessToken) source;
    final ExtendedHierarchicalStreamWriter writer = (ExtendedHierarchicalStreamWriter) writerOrig
            .underlyingWriter();/*www  .  java 2  s.c  om*/

    writer.startNode(OAuth2AccessToken.ACCESS_TOKEN, String.class);
    writer.setValue(formattedValue(token.getValue()));
    writer.endNode();

    writer.startNode(OAuth2AccessToken.TOKEN_TYPE, String.class);
    writer.setValue(formattedValue(token.getTokenType()));
    writer.endNode();

    final OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null) {
        writer.startNode(OAuth2AccessToken.REFRESH_TOKEN, String.class);
        writer.setValue(formattedValue(refreshToken.getValue()));
        writer.endNode();

    }
    final Date expiration = token.getExpiration();
    if (expiration != null) {
        final long now = System.currentTimeMillis();
        writer.startNode(OAuth2AccessToken.EXPIRES_IN, Integer.class);
        writer.setValue(String.valueOf((expiration.getTime() - now) / 1000));
        writer.endNode();
    }
    final Set<String> scope = token.getScope();
    if (scope != null && !scope.isEmpty()) {
        final StringBuffer scopes = new StringBuffer();
        for (final String s : scope) {
            Assert.hasLength(s, "Scopes cannot be null or empty. Got " + scope);
            scopes.append(s);
            scopes.append(' ');
        }

        writer.startNode(OAuth2AccessToken.SCOPE, String.class);
        writer.setValue(formattedValue(scopes.substring(0, scopes.length() - 1)));
        writer.endNode();
    }
    final Map<String, Object> additionalInformation = token.getAdditionalInformation();
    for (final String key : additionalInformation.keySet()) {
        writer.startNode(key, String.class);
        writer.setValue(formattedValue(String.valueOf(additionalInformation.get(key))));
        writer.endNode();
    }
}

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 ww .  j av a 2s  . 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:com.avego.oauth.migration.OauthDataMigrator.java

/**
 * This migrates the oauth access tokens
 * @throws IOException If an IO error occurs such as when serializing/deserializing data
 * @throws ClassNotFoundException If a class not found when serializing/deserializing data
 * @throws InvocationTargetException If an invocation target exception occurs when using reflection to convert to the new objects
 * @throws IllegalAccessException If an IllegalAccessException exception occurs when using reflection to convert to the new objects
 * @throws NoSuchMethodException If a NoSuchMethodException exception occurs when using reflection to convert to the new objects
 * @throws InstantiationException/*  www  .  j  a  v  a  2 s  .co m*/
 * @throws IllegalArgumentException
 */
@SuppressWarnings("unchecked")
protected void migrateAccessTokens() throws IOException, ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, IllegalArgumentException, InstantiationException {

    int numTokens = this.dao.countUnmigratedAccessTokens();
    int pageSize = PAGE_SIZE;

    int numMigrated = 0;
    System.out.println("Starting Migrating " + numTokens + " access token(s) ...");

    while (numTokens > 0) {

        List<OauthAccessTokenRecord> accessTokens = this.dao.getUnmigratedOauthAccessTokenRecords(pageSize);

        for (OauthAccessTokenRecord tokenRecord : accessTokens) {

            String oldTokenId = tokenRecord.getTokenId();
            System.out.println("Migrating token with id: " + oldTokenId + "...");

            String newTokenId = this.dao.generateNewTokenKey(tokenRecord.getTokenId());
            String newRefreshToken = this.dao.generateNewTokenKey(tokenRecord.getRefreshToken());

            if (this.removeRefreshTokens) {
                newRefreshToken = null;
            }

            System.out.println("New token id: " + newTokenId);
            System.out.println("New refresh token id: " + newRefreshToken);

            // deserialize the token, note this is backward compatible
            OAuth2AccessToken accessToken = null;
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(tokenRecord.getToken()));
            try {
                Object obj = ois.readObject();
                accessToken = (OAuth2AccessToken) obj;
            } finally {
                ois.close();
            }

            // replace the token value in the access token..
            if (this.serializeNewTokenValues) {

                Constructor<OAuth2AccessToken> constructor = null;

                // see if it has a set value method
                Method setValueMethod = MethodUtils.getAccessibleMethod(accessToken.getClass(), "setValue",
                        String.class);
                if (setValueMethod != null) {
                    Object res = setValueMethod.invoke(accessToken, newTokenId);
                    if (res != null && res instanceof OAuth2AccessToken) {
                        accessToken = (OAuth2AccessToken) res;
                    }
                } else {

                    // look for constructors that we can use
                    constructor = (Constructor<OAuth2AccessToken>) ConstructorUtils
                            .getAccessibleConstructor(accessToken.getClass(), String.class);
                    if (constructor != null) {

                        OAuth2AccessToken newAccessToken = constructor.newInstance(newTokenId);

                        // we also need to invoke setters for other fields
                        MethodUtils.invokeMethod(newAccessToken, "setAdditionalInformation",
                                accessToken.getAdditionalInformation());
                        MethodUtils.invokeMethod(newAccessToken, "setExpiration", accessToken.getExpiration());
                        MethodUtils.invokeMethod(newAccessToken, "setScope", accessToken.getScope());
                        MethodUtils.invokeMethod(newAccessToken, "setTokenType", accessToken.getTokenType());

                        accessToken = newAccessToken;

                    } else {
                        throw new IllegalStateException("The access token with the class: "
                                + accessToken.getClass().getName()
                                + " did not have a set value method nor a constructor taking a string which we need to update its token value");
                    }

                }

                // we also need to overwrite the refresh token
                String newRefreshTokenValue = this.dao
                        .generateNewTokenKey(accessToken.getRefreshToken().getValue());
                OAuth2RefreshToken refreshToken = replaceOAuth2RefreshTokenValue(accessToken.getRefreshToken(),
                        newRefreshTokenValue);
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", refreshToken);
            }

            if (this.removeRefreshTokens) {
                MethodUtils.invokeMethod(accessToken, "setRefreshToken", new Object[] { null },
                        new Class<?>[] { OAuth2RefreshToken.class });
            }

            byte[] tokenData = SerializationUtils.serialize((Serializable) accessToken);

            // deserialise the authenticated, this is NOT backward compatible so we have to read using a diff class loader
            OAuth2Authentication auth = deserializeOAuth2Authentication(tokenRecord.getAuthentication());
            byte[] authData = SerializationUtils.serialize(auth);

            // this does the actual migration of the token
            this.dao.updateOauthAccessToken(oldTokenId, newTokenId, newRefreshToken, tokenData, authData);

            System.out.println("Migrated token with id: " + oldTokenId);
            numMigrated++;
            System.out.println("");
        }
        numTokens = this.dao.countUnmigratedAccessTokens();
    }

    System.out.println("Finished Migrating " + numMigrated + " access token(s).");

}

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

public String buildRedirectURI(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken,
        Authentication authUser) {/*from   w  w w.  j av a2s  .co  m*/

    String requestedRedirect = authorizationRequest.getRedirectUri();
    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }

    StringBuilder url = new StringBuilder();
    url.append("token_type=").append(encode(accessToken.getTokenType()));

    //only append access token if grant_type is implicit
    //or token is part of the response type
    if (authorizationRequest.getResponseTypes().contains("token")) {
        url.append("&access_token=").append(encode(accessToken.getValue()));
    }

    if (accessToken instanceof CompositeToken
            && authorizationRequest.getResponseTypes().contains(CompositeToken.ID_TOKEN)) {
        url.append("&").append(CompositeToken.ID_TOKEN).append("=")
                .append(encode(((CompositeToken) accessToken).getIdTokenValue()));
    }

    if (authorizationRequest.getResponseTypes().contains("code")) {
        String code = generateCode(authorizationRequest, authUser);
        url.append("&code=").append(encode(code));
    }

    String state = authorizationRequest.getState();
    if (state != null) {
        url.append("&state=").append(encode(state));
    }

    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        url.append("&expires_in=").append(expires_in);
    }

    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        url.append("&" + OAuth2Utils.SCOPE + "=")
                .append(encode(OAuth2Utils.formatParameterList(accessToken.getScope())));
    }

    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            url.append("&" + encode(key) + "=" + encode(value.toString()));
        }
    }

    if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) {
        HttpHost httpHost = URIUtils.extractHost(URI.create(requestedRedirect));
        String sessionState = openIdSessionStateCalculator.calculate(
                ((UaaPrincipal) authUser.getPrincipal()).getId(), authorizationRequest.getClientId(),
                httpHost.toURI());

        url.append("&session_state=").append(sessionState);
    }

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(requestedRedirect);
    String existingFragment = builder.build(true).getFragment();
    if (StringUtils.hasText(existingFragment)) {
        existingFragment = existingFragment + "&" + url.toString();
    } else {
        existingFragment = url.toString();
    }
    builder.fragment(existingFragment);
    // Do not include the refresh token (even if there is one)
    return builder.build(true).toUriString();
}

From source file:org.opentestsystem.shared.security.oauth.resource.SbacTokenConverter.java

@Override
public Map<String, ?> convertAccessToken(final OAuth2AccessToken token,
        final OAuth2Authentication authentication) {
    final Map<String, Object> response = Maps.newHashMap();
    final OAuth2Request clientToken = authentication.getOAuth2Request();

    if (!authentication.isClientOnly()) {
        response.putAll(//w  w w.ja  va 2  s.  c o m
                this.userTokenConverter.convertUserAuthentication(authentication.getUserAuthentication()));
    }

    if (token.getScope() != null) {
        response.put(SCOPE, token.getScope());
    }

    if (token.getExpiration() != null) {
        response.put(EXPIRES, token.getExpiration().getTime() / 1000);
    }

    response.putAll(token.getAdditionalInformation());

    response.put(CLIENT_ID, clientToken.getClientId());
    if (clientToken.getResourceIds() != null && !clientToken.getResourceIds().isEmpty()) {
        response.put(AUD, clientToken.getResourceIds());
    }
    return response;
}

From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java

private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) {

    Map<String, Object> vars = new LinkedHashMap<String, Object>();
    Map<String, String> keys = new HashMap<String, String>();

    if (accessToken == null) {
        throw new InvalidRequestException("An implicit grant could not be made");
    }// www. j a  v a2s.  c  o  m

    vars.put("access_token", accessToken.getValue());
    vars.put("token_type", accessToken.getTokenType());
    String state = authorizationRequest.getState();

    if (state != null) {
        vars.put("state", state);
    }
    Date expiration = accessToken.getExpiration();
    if (expiration != null) {
        long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000;
        vars.put("expires_in", expires_in);
    }
    String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE);
    if (originalScope == null
            || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) {
        vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope()));
    }
    Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
    for (String key : additionalInformation.keySet()) {
        Object value = additionalInformation.get(key);
        if (value != null) {
            keys.put("extra_" + key, key);
            vars.put("extra_" + key, value);
        }
    }
    // Do not include the refresh token (even if there is one)
    return append(authorizationRequest.getRedirectUri(), vars, keys, true);
}