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:com.cedac.security.oauth2.provider.token.store.MongoTokenStore.java

public void storeAccessToken(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    String refreshToken = null;//from  w w w.j a v a2 s .co m
    if (accessToken.getRefreshToken() != null) {
        refreshToken = accessToken.getRefreshToken().getValue();
    }

    if (readAccessToken(accessToken.getValue()) != null) {
        removeAccessToken(accessToken.getValue());
    }

    DBObject token = new BasicDBObject();
    token.put(tokenIdFieldName, extractTokenKey(accessToken.getValue()));
    token.put(tokenFieldName, serializeAccessToken(accessToken));
    token.put(authenticationIdFieldName, authenticationKeyGenerator.extractKey(authentication));
    if (!authentication.isClientOnly()) {
        token.put(usernameFieldName, authentication.getName());
    } else {
        token.put(usernameFieldName, null);
    }
    token.put(clientIdFieldName, authentication.getOAuth2Request().getClientId());
    token.put(authenticationFieldName, serializeAuthentication(authentication));
    token.put(refreshTokenFieldName, extractTokenKey(refreshToken));

    getAccessTokenCollection().insert(token, writeConcern);
}

From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java

/**
 * Verify that authentication is successful.
 *///from   w  w  w .  j  ava 2  s.c  om
@Test
public void testSuccessfulAuthentication() {
    OAuth2RestTemplate restTemplate = AuthenticationUtil.getClientCredentials();
    OAuth2AccessToken token = null;
    try {
        token = restTemplate.getAccessToken();
    } catch (OAuth2AccessDeniedException ex) {
        if (ex.getCause() instanceof ResourceAccessException) {
            fail("It appears that the server may not be running. Please start it before running tests");
        } else {
            fail(ex.getMessage());
        }
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
    assertNotNull(token.getValue());
}

From source file:org.cloudfoundry.identity.uaa.integration.ScimGroupEndpointsIntegrationTests.java

private HttpHeaders getAuthenticatedHeaders(OAuth2AccessToken token) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + token.getValue());
    return headers;
}

From source file:org.openmhealth.shim.ihealth.IHealthShim.java

@Override
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate,
        ShimDataRequest shimDataRequest) throws ShimException {

    final IHealthDataTypes dataType;
    try {//from w ww  .j  a v  a  2 s.c  o m
        dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerException | IllegalArgumentException e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey()
                + " in shimDataRequest, cannot retrieve data.");
    }

    OffsetDateTime now = OffsetDateTime.now();
    OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1)
            : shimDataRequest.getStartDateTime();
    OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1)
            : shimDataRequest.getEndDateTime();

    /*
    The physical activity point handles start and end datetimes differently than the other endpoints. It
    requires use to include the range until the beginning of the next day.
     */
    if (dataType == PHYSICAL_ACTIVITY) {

        endDate = endDate.plusDays(1);
    }

    // SC and SV values are client-based keys that are unique to each endpoint within a project
    String scValue = getScValue();
    List<String> svValues = getSvValues(dataType);

    List<JsonNode> responseEntities = newArrayList();

    int i = 0;

    // We iterate because one of the measures (Heart rate) comes from multiple endpoints, so we submit
    // requests to each of these endpoints, map the responses separately and then combine them
    for (String endPoint : dataType.getEndPoint()) {

        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL);

        // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using
        // getData to trigger Spring to conduct the OAuth exchange
        String userId = "uk";

        if (shimDataRequest.getAccessParameters() != null) {

            OAuth2AccessToken token = SerializationUtils
                    .deserialize(shimDataRequest.getAccessParameters().getSerializedToken());

            userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID"));
            uriBuilder.queryParam("access_token", token.getValue());
        }

        uriBuilder.path("/user/").path(userId + "/").path(endPoint)
                .queryParam("client_id", restTemplate.getResource().getClientId())
                .queryParam("client_secret", restTemplate.getResource().getClientSecret())
                .queryParam("start_time", startDate.toEpochSecond())
                .queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default")
                .queryParam("sc", scValue).queryParam("sv", svValues.get(i));

        ResponseEntity<JsonNode> responseEntity;

        try {
            URI url = uriBuilder.build().encode().toUri();
            responseEntity = restTemplate.getForEntity(url, JsonNode.class);
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            // FIXME figure out how to handle this
            logger.error("A request for iHealth data failed.", e);
            throw e;
        }

        if (shimDataRequest.getNormalize()) {

            IHealthDataPointMapper mapper;

            switch (dataType) {

            case PHYSICAL_ACTIVITY:
                mapper = new IHealthPhysicalActivityDataPointMapper();
                break;
            case BLOOD_GLUCOSE:
                mapper = new IHealthBloodGlucoseDataPointMapper();
                break;
            case BLOOD_PRESSURE:
                mapper = new IHealthBloodPressureDataPointMapper();
                break;
            case BODY_WEIGHT:
                mapper = new IHealthBodyWeightDataPointMapper();
                break;
            case BODY_MASS_INDEX:
                mapper = new IHealthBodyMassIndexDataPointMapper();
                break;
            case STEP_COUNT:
                mapper = new IHealthStepCountDataPointMapper();
                break;
            case SLEEP_DURATION:
                mapper = new IHealthSleepDurationDataPointMapper();
                break;
            case HEART_RATE:
                // there are two different mappers for heart rate because the data can come from two endpoints
                if (endPoint == "bp.json") {
                    mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper();
                    break;
                } else if (endPoint == "spo2.json") {
                    mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper();
                    break;
                }
            case OXYGEN_SATURATION:
                mapper = new IHealthOxygenSaturationDataPointMapper();
                break;
            default:
                throw new UnsupportedOperationException();
            }

            responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody())));

        } else {
            responseEntities.add(responseEntity.getBody());
        }

        i++;

    }

    return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities));
}

From source file:org.saiku.web.AuthTest.java

@Test
public void testHappyDay() throws Exception {
    int port = 9999;
    Client client = Client.create();/*from   ww w .java 2  s. co m*/
    client.setFollowRedirects(false);

    MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
    formData.add("grant_type", "password");
    formData.add("client_id", "my-trusted-client");
    formData.add("username", "marissa");
    formData.add("password", "koala");
    WebResource webResource = client.resource("http://localhost:9999/");
    ClientResponse response = webResource.path("/saiku/oauth/authorize")
            .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData);
    assertEquals(200, response.getClientResponseStatus().getStatusCode());
    assertEquals("no-store", response.getHeaders().getFirst("Cache-Control"));

    DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
    OAuth2AccessToken accessToken = serializationService
            .deserializeJsonAccessToken(response.getEntityInputStream());

    //now try and use the token to access a protected resource.

    //first make sure the resource is actually protected.
    response = client.resource("http://localhost:" + port + "/saiku/serverdocs/index.html")
            .get(ClientResponse.class);
    assertFalse(200 == response.getClientResponseStatus().getStatusCode());

    //now make sure an authorized request is valid.
    response = client.resource("http://localhost:" + port + "/saiku/serverdocs/index.html")
            .header("Authorization", String.format("OAuth %s", accessToken.getValue()))
            .get(ClientResponse.class);
    assertEquals(200, response.getClientResponseStatus().getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java

@Test
public void testDecodeToken() {
    AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();
    BasicCookieStore cookies = new BasicCookieStore();

    URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code")
            .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId())
            .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build();
    ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), getHeaders(cookies));
    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")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(/*from  w w  w.java  2 s  .  c o  m*/
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }

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

    if (response.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : response.getHeaders().get("Set-Cookie")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }
    // 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());

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", testAccounts.getUserName());
    formData.add("password", testAccounts.getPassword());
    formData.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

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

    if (result.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : result.getHeaders().get("Set-Cookie")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }

    response = serverRunning.getForString(result.getHeaders().getLocation().toString(), getHeaders(cookies));
    if (response.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : response.getHeaders().get("Set-Cookie")) {
            int nameLength = cookie.indexOf('=');
            cookies.addCookie(
                    new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1)));
        }
    }
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("<h1>Application Authorization</h1>"));

        formData.clear();
        formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody()));
        formData.add(USER_OAUTH_APPROVAL, "true");
        result = serverRunning.postForResponse("/oauth/authorize", getHeaders(cookies), 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();
    }
    assertTrue("Wrong location: " + location,
            location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+"));

    formData.clear();
    formData.add("client_id", resource.getClientId());
    formData.add("redirect_uri", resource.getPreEstablishedRedirectUri());
    formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody());

    HttpHeaders headers = new HttpHeaders();
    formData = new LinkedMultiValueMap<String, String>();
    headers.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    formData.add("token", accessToken.getValue());

    tokenResponse = serverRunning.postForMap("/check_token", formData, headers);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    @SuppressWarnings("unchecked")
    Map<String, String> map = tokenResponse.getBody();
    assertNotNull(map.get("iss"));
    assertEquals(testAccounts.getUserName(), map.get("user_name"));
    assertEquals(testAccounts.getEmail(), map.get("email"));

    // Test that Spring's default converter can create an auth from the response.
    Authentication auth = (new DefaultUserAuthenticationConverter()).extractAuthentication(map);
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    // insert into oauth_access_token (token_id, token, authentication_id, authentication, refresh_token) values (?, ?, ?, ?, ?)
    String refreshToken = null;/*w  w  w  .j  a v  a 2s  .  c o m*/
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }
    final String name = (authentication.getUserAuthentication() == null) ? null
            : authentication.getUserAuthentication().getName();
    final BasicDBObject document = new BasicDBObject();
    document.put("token_id", token.getValue());
    document.put("token", serialize(token));
    document.put("authentication_id", null);
    document.put("authentication", serialize(authentication));
    document.put("refresh_token", refreshToken);
    document.put("name", name);
    final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
    collection.insert(document);
}

From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java

@Test
public void testValidPasswordGrant() {
    OAuth2AccessToken accessToken = getUserToken(null);

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    HttpHeaders tokenHeaders = new HttpHeaders();
    ClientCredentialsResourceDetails resource = testAccounts.getClientCredentialsResource("app", null, "app",
            "appclientsecret");
    tokenHeaders.set("Authorization",
            testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret()));
    formData.add("token", accessToken.getValue());

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/check_token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    assertNotNull(tokenResponse.getBody());
    System.out.println(tokenResponse.getBody());

    @SuppressWarnings("unchecked")
    Map<String, String> map = tokenResponse.getBody();
    assertNotNull(map.get("iss"));
    assertEquals(testAccounts.getUserName(), map.get("user_name"));
    assertEquals(testAccounts.getEmail(), map.get("email"));
}

From source file:com.cedac.security.oauth2.provider.token.store.TokenStoreBaseTests.java

@Test
public void testStoreAccessToken() {
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(
            RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
    OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
    getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication);

    OAuth2AccessToken actualOAuth2AccessToken = getTokenStore().readAccessToken("testToken");
    assertEquals(expectedOAuth2AccessToken, actualOAuth2AccessToken);
    assertEquals(expectedAuthentication, getTokenStore().readAuthentication(expectedOAuth2AccessToken));
    getTokenStore().removeAccessToken(expectedOAuth2AccessToken);
    assertNull(getTokenStore().readAccessToken("testToken"));
    assertNull(getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()));
}