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

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

Introduction

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

Prototype

String getValue();

Source Link

Usage

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  a  2s.c o  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.apigw.authserver.svc.impl.TokenServicesImplTest.java

@Test
@DirtiesContext//from w w  w . jav  a2  s.c o  m
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:com.vivastream.security.oauth2.provider.token.store.DynamoDBTokenStore.java

public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    OAuth2AccessToken accessToken = null;

    String key = authenticationKeyGenerator.extractKey(authentication);
    try {/*from   w w  w. j  a  v a 2  s .  co m*/
        String accessTokenId = dynamoDBTemplate.queryUnique(schema.getAccessTableName(),
                schema.getAccessIndexAuthenticationId(), // 
                Collections.singletonMap(schema.getAccessColumnAuthenticationId(),
                        new Condition().withComparisonOperator(ComparisonOperator.EQ)
                                .withAttributeValueList(new AttributeValue(key))), // 
                new ObjectExtractor<String>() {

                    public String extract(Map<String, AttributeValue> values) {
                        return values.get(schema.getAccessColumnTokenId()).getS();
                    }
                });
        accessToken = dynamoDBTemplate.get(schema.getAccessTableName(),
                Collections.singletonMap(schema.getAccessColumnTokenId(), new AttributeValue(accessTokenId)),
                new ObjectExtractor<OAuth2AccessToken>() {

                    public OAuth2AccessToken extract(Map<String, AttributeValue> values) {
                        return deserializeAccessToken(values.get(schema.getAccessColumnToken()).getB());
                    }
                });
    } catch (EmptyResultDataAccessException | IncorrectResultSizeDataAccessException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to find access token for authentication " + authentication);
        }
    } catch (IllegalArgumentException e) {
        LOG.error("Could not extract access token for authentication " + authentication, e);
    }

    if (accessToken != null
            && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
        // Keep the store consistent (maybe the same user is represented by this authentication but the details have
        // changed)
        storeAccessToken(accessToken, authentication);
    }
    return accessToken;
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

@SuppressWarnings("restriction")
private Map<String, Object> getUserInfo(String user) {
    //      String userJson = getRestTemplate().getForObject(getUrl("/v2/users/{guid}"), String.class, user);
    //      Map<String, Object> userInfo = (Map<String, Object>) JsonUtil.convertJsonToMap(userJson);
    //      return userInfo();
    //TODO: remove this temporary hack once the /v2/users/ uri can be accessed by mere mortals
    String userJson = "{}";
    OAuth2AccessToken accessToken = oauthClient.getToken();
    if (accessToken != null) {
        String tokenString = accessToken.getValue();
        int x = tokenString.indexOf('.');
        int y = tokenString.indexOf('.', x + 1);
        String encodedString = tokenString.substring(x + 1, y);
        try {/*from   w w w.j  ava 2s  . c  om*/
            byte[] decodedBytes = new sun.misc.BASE64Decoder().decodeBuffer(encodedString);
            userJson = new String(decodedBytes, 0, decodedBytes.length, "UTF-8");
        } catch (IOException e) {
        }
    }
    return (JsonUtil.convertJsonToMap(userJson));
}

From source file:com.vivastream.security.oauth2.provider.token.store.DynamoDBTokenStore.java

public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    String refreshToken = null;//from  www.  j  av a2  s  . c  o  m
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }

    // the JdbcTokenStore removes the existing token for this token_id [if it exists]
    // We'll avoid doing so for now, unless a compelling reason to do otherwise presents itself
    //        if (readAccessToken(token.getValue()) != null) {
    //            removeAccessToken(token.getValue());
    //        }

    Map<String, AttributeValueUpdate> updates = new HashMap<String, AttributeValueUpdate>();
    updates.put(schema.getAccessColumnToken(), new AttributeValueUpdate(
            new AttributeValue().withB(serializeAccessToken(token)), AttributeAction.PUT));
    DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnAuthenticationId(),
            authenticationKeyGenerator.extractKey(authentication));
    if (authentication.isClientOnly() || authentication.getName() == null
            || authentication.getName().length() == 0) {
        DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnUserName(),
                schema.getAccessNullUserToken());
        updates.put(schema.getAccessColumnIsNullUser(), new AttributeValueUpdate(
                new AttributeValue().withN(schema.getAccessIsNullUserTrueToken()), AttributeAction.PUT));
    } else {
        DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnUserName(), authentication.getName());
        DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnIsNullUser(), null);
    }

    DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnClientId(),
            authentication.getOAuth2Request().getClientId());
    updates.put(schema.getAccessColumnAuthentication(), new AttributeValueUpdate(
            new AttributeValue().withB(serializeAuthentication(authentication)), AttributeAction.PUT));
    DynamoDBUtils.nullSafeUpdateS(updates, schema.getAccessColumnRefreshToken(), extractTokenKey(refreshToken));

    dynamoDBTemplate.update(schema.getAccessTableName(), // 
            Collections.singletonMap(schema.getAccessColumnTokenId(),
                    new AttributeValue(extractTokenKey(token.getValue()))), // 
            updates);
}

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 v  a2  s .  co  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.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static String getClientCredentialsToken(String baseUrl, String clientId, String clientSecret)
        throws Exception {
    RestTemplate template = new RestTemplate();
    template.setRequestFactory(new StatelessRequestFactory());
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("grant_type", "client_credentials");
    formData.add("client_id", clientId);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes())));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = template.exchange(baseUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity(formData, headers), Map.class);

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
    return accessToken.getValue();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static Map<String, String> getAuthorizationCodeTokenMap(ServerRunning serverRunning,
        UaaTestAccounts testAccounts, String clientId, String clientSecret, String username, String password,
        String tokenResponseType, String jSessionId, String redirectUri, boolean callCheckToken)
        throws Exception {
    // TODO Fix to use json API rather than HTML
    HttpHeaders headers = new HttpHeaders();
    if (StringUtils.hasText(jSessionId)) {
        headers.add("Cookie", "JSESSIONID=" + jSessionId);
    }//from  w  w  w .j a  v  a  2 s  .c om
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    String mystateid = "mystateid";
    ServerRunning.UriBuilder builder = serverRunning.buildUri("/oauth/authorize")
            .queryParam("response_type", "code").queryParam("state", mystateid)
            .queryParam("client_id", clientId);
    if (StringUtils.hasText(redirectUri)) {
        builder = builder.queryParam("redirect_uri", redirectUri);
    }
    URI uri = builder.build();

    ResponseEntity<Void> result = serverRunning.createRestTemplate().exchange(uri.toString(), HttpMethod.GET,
            new HttpEntity<>(null, headers), Void.class);

    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();

    if (result.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : result.getHeaders().get("Set-Cookie")) {
            assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
            headers.add("Cookie", cookie);
        }
    }

    ResponseEntity<String> response = serverRunning.getForString(location, headers);

    if (response.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : response.getHeaders().get("Set-Cookie")) {
            headers.add("Cookie", cookie);
        }
    }

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    if (!StringUtils.hasText(jSessionId)) {
        // should be directed to the login screen...
        assertTrue(response.getBody().contains("/login.do"));
        assertTrue(response.getBody().contains("username"));
        assertTrue(response.getBody().contains("password"));
        String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody());

        formData.add("username", username);
        formData.add("password", password);
        formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);

        // Should be redirected to the original URL, but now authenticated
        result = serverRunning.postForResponse("/login.do", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());

        headers.remove("Cookie");
        if (result.getHeaders().containsKey("Set-Cookie")) {
            for (String cookie : result.getHeaders().get("Set-Cookie")) {
                headers.add("Cookie", cookie);
            }
        }
    }

    response = serverRunning.createRestTemplate().exchange(result.getHeaders().getLocation().toString(),
            HttpMethod.GET, new HttpEntity<>(null, headers), String.class);

    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("<h1>Application Authorization</h1>"));

        formData.clear();
        formData.add(USER_OAUTH_APPROVAL, "true");
        formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody()));
        result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = result.getHeaders().getLocation().toString();
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = response.getHeaders().getLocation().toString();
    }
    if (StringUtils.hasText(redirectUri)) {
        assertTrue("Wrong location: " + location, location.matches(redirectUri + ".*code=.+"));
    }

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("grant_type", "authorization_code");
    if (StringUtils.hasText(redirectUri)) {
        formData.add("redirect_uri", redirectUri);
    }
    if (StringUtils.hasText(tokenResponseType)) {
        formData.add("response_type", tokenResponseType);
    }
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set("Authorization", testAccounts.getAuthorizationHeader(clientId, clientSecret));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody());
    Map<String, String> body = tokenResponse.getBody();

    formData = new LinkedMultiValueMap<>();
    headers.set("Authorization", testAccounts.getAuthorizationHeader(clientId, clientSecret));
    formData.add("token", accessToken.getValue());

    if (callCheckToken) {
        tokenResponse = serverRunning.postForMap("/check_token", formData, headers);
        assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
        //System.err.println(tokenResponse.getBody());
        assertNotNull(tokenResponse.getBody().get("iss"));
    }
    return body;
}

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

@RequestMapping(value = "/check_token")
@ResponseBody/* w  w w.j av  a 2 s  .com*/
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;
}