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

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

Introduction

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

Prototype

String BEARER_TYPE

To view the source code for org.springframework.security.oauth2.common OAuth2AccessToken BEARER_TYPE.

Click Source Link

Usage

From source file:it.reply.orchestrator.controller.DeploymentControllerTest.java

@Test
public void getDeploymentWithOutputSuccessfully() throws Exception {

    String deploymentId = "mmd34483-d937-4578-bfdb-ebe196bf82dd";
    Deployment deployment = ControllerTestUtils.createDeployment(deploymentId);
    Map<String, String> outputs = Maps.newHashMap();
    String key = "server_ip";
    String value = "10.0.0.1";
    outputs.put(key, JsonUtility.serializeJson(value));
    deployment.setOutputs(outputs);//  w  ww  .ja v a  2 s . c  o m
    deployment.setStatus(Status.CREATE_FAILED);
    deployment.setStatusReason("Some reason");
    Mockito.when(deploymentService.getDeployment(deploymentId)).thenReturn(deployment);

    mockMvc.perform(get("/deployments/" + deploymentId).header(HttpHeaders.AUTHORIZATION,
            OAuth2AccessToken.BEARER_TYPE + " <access token>")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.outputs", Matchers.hasEntry(key, value)))

            .andDo(document("deployment", preprocessResponse(prettyPrint()),

                    responseFields(fieldWithPath("links[]").ignored(),

                            fieldWithPath("uuid").description("The unique identifier of a resource"),
                            fieldWithPath("creationTime").description(
                                    "Creation date-time (http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14)"),
                            fieldWithPath("updateTime").description("Update date-time"),
                            fieldWithPath("status").description(
                                    "The status of the deployment. (http://indigo-dc.github.io/orchestrator/apidocs/it/reply/orchestrator/enums/Status.html)"),
                            fieldWithPath("statusReason").description(
                                    "Verbose explanation of reason that lead to the deployment status (Present only if the deploy is in some error status)"),
                            fieldWithPath("task").description(
                                    "The current step of the deployment process. (http://indigo-dc.github.io/orchestrator/apidocs/it/reply/orchestrator/enums/Task.html)"),
                            fieldWithPath("callback").description(
                                    "The endpoint used by the orchestrator to notify the progress of the deployment process."),
                            fieldWithPath("outputs").description("The outputs of the TOSCA document"),
                            fieldWithPath("links[]").ignored())));
}

From source file:it.reply.orchestrator.controller.DeploymentControllerTest.java

@Test
public void getDeploymentNotFound() throws Exception {

    String deploymentId = "mmd34483-d937-4578-bfdb-ebe196bf82dd";
    Mockito.when(deploymentService.getDeployment(deploymentId)).thenThrow(new NotFoundException("Message"));

    mockMvc.perform(get("/deployments/" + deploymentId).header(HttpHeaders.AUTHORIZATION,
            OAuth2AccessToken.BEARER_TYPE + " <access token>")).andExpect(status().isNotFound())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.code", is(404)))
            .andDo(document("deployment-not-found", preprocessResponse(prettyPrint()),
                    responseFields(fieldWithPath("code").description("The HTTP status code"),
                            fieldWithPath("title").description("The HTTP status name"),
                            fieldWithPath("message")
                                    .description("A displayable message describing the error"))))
            .andExpect(jsonPath("$.title", is("Not Found"))).andExpect(jsonPath("$.message", is("Message")));
}

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

@Test
@DirtiesContext//  w ww.  j  a v a 2  s .c  om
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:it.reply.orchestrator.controller.DeploymentControllerTest.java

@Test
public void createDeploymentSuccessfully() throws Exception {

    DeploymentRequest request = new DeploymentRequest();
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("cpus", 1);
    request.setParameters(parameters);//from w w  w .  j  av  a2s.  com
    request.setTemplate("template");
    request.setCallback("http://localhost:8080/callback");

    Deployment deployment = ControllerTestUtils.createDeployment();
    deployment.setCallback(request.getCallback());
    deployment.setStatus(Status.CREATE_IN_PROGRESS);
    Mockito.when(deploymentService.createDeployment(request)).thenReturn(deployment);

    mockMvc.perform(post("/deployments").contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(request))
            .header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " <access token>"))

            .andDo(document("create-deployment", preprocessRequest(prettyPrint()),
                    preprocessResponse(prettyPrint()),
                    requestFields(
                            fieldWithPath("template")
                                    .description("A string containing a TOSCA YAML-formatted template"),
                            fieldWithPath("parameters").optional().description(
                                    "The input parameters of the deployment(Map of String, Object)"),
                            fieldWithPath("callback").description("The deployment callback URL (optional)")),
                    responseFields(fieldWithPath("links[]").ignored(),
                            fieldWithPath("uuid").description("The unique identifier of a resource"),
                            fieldWithPath("creationTime").description(
                                    "Creation date-time (http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14)"),
                            fieldWithPath("updateTime").description(
                                    "Update date-time (http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14)"),
                            fieldWithPath("status").description(
                                    "The status of the deployment. (http://indigo-dc.github.io/orchestrator/apidocs/it/reply/orchestrator/enums/Status.html)"),
                            fieldWithPath("task").description(
                                    "The current step of the deployment process. (http://indigo-dc.github.io/orchestrator/apidocs/it/reply/orchestrator/enums/Task.html)"),
                            fieldWithPath("outputs").description("The outputs of the TOSCA document"),
                            fieldWithPath("callback").description(
                                    "The endpoint used by the orchestrator to notify the progress of the deployment process."),
                            fieldWithPath("links[]").ignored())));

}

From source file:it.reply.orchestrator.controller.DeploymentControllerTest.java

@Test
public void updateDeploymentSuccessfully() throws Exception {

    DeploymentRequest request = new DeploymentRequest();
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("cpus", 1);
    request.setParameters(parameters);/*from  w w  w.ja v  a 2 s  .c om*/
    request.setTemplate("template");
    request.setCallback("http://localhost:8080/callback");

    String deploymentId = "mmd34483-d937-4578-bfdb-ebe196bf82dd";
    Mockito.doNothing().when(deploymentService).updateDeployment(deploymentId, request);

    mockMvc.perform(put("/deployments/" + deploymentId).contentType(MediaType.APPLICATION_JSON)
            .content(TestUtil.convertObjectToJsonBytes(request))
            .header(HttpHeaders.AUTHORIZATION, OAuth2AccessToken.BEARER_TYPE + " <access token>"))

            .andDo(document("update-deployment", preprocessRequest(prettyPrint()),
                    preprocessResponse(prettyPrint()),
                    requestFields(
                            fieldWithPath("template")
                                    .description("A string containing a TOSCA YAML-formatted template"),
                            fieldWithPath("parameters").optional().description(
                                    "The input parameters of the deployment (Map of String, Object)"),
                            fieldWithPath("callback").description("The deployment callback URL (optional)"))));

}

From source file:it.reply.orchestrator.controller.DeploymentControllerTest.java

@Test
public void deleteDeployment() throws Exception {

    String deploymentId = "mmd34483-d937-4578-bfdb-ebe196bf82dd";
    Mockito.doNothing().when(deploymentService).deleteDeployment(deploymentId);

    mockMvc.perform(delete("/deployments/" + deploymentId).header(HttpHeaders.AUTHORIZATION,
            OAuth2AccessToken.BEARER_TYPE + " <access token>")).andExpect(status().isNoContent())
            .andDo(document("delete-deployment", preprocessRequest(prettyPrint()),
                    preprocessResponse(prettyPrint())));

}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

/**
 * This method is implemented to support older API calls that assume the
 * presence of a token store/* w  ww .  jav a2s  .com*/
 */
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
    Map<String, Object> claims = getClaimsForToken(accessToken);

    // Expiry is verified by check_token
    OpenIdToken token = new OpenIdToken(accessToken);
    token.setTokenType(OAuth2AccessToken.BEARER_TYPE);
    Integer exp = (Integer) claims.get(EXP);
    if (null != exp) {
        token.setExpiration(new Date(exp.longValue() * 1000l));
    }

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);
    if (null != scopes && scopes.size() > 0) {
        token.setScope(new HashSet<String>(scopes));
    }

    String email = (String) claims.get(EMAIL);

    // Only check user access tokens
    if (null != email) {
        String userId = (String) claims.get(USER_ID);

        UaaUser user = userDatabase.retrieveUserById(userId);

        Integer accessTokenIssuedAt = (Integer) claims.get(IAT);
        long accessTokenIssueDate = accessTokenIssuedAt.longValue() * 1000l;

        // If the user changed their password, expire the access token
        if (user.getModified().after(new Date(accessTokenIssueDate))) {
            logger.debug("User was last modified at " + user.getModified() + " access token was issued at "
                    + new Date(accessTokenIssueDate));
            throw new InvalidTokenException("Invalid access token (password changed): " + accessToken);
        }

        // Check approvals to make sure they're all valid, approved and not
        // more recent
        // than the token itself
        String clientId = (String) claims.get(CLIENT_ID);
        ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

        @SuppressWarnings("unchecked")
        ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
        Set<String> autoApprovedScopes = getAutoApprovedScopes(claims.get(GRANT_TYPE), tokenScopes, client);
        if (autoApprovedScopes.containsAll(tokenScopes)) {
            return token;
        }
        checkForApproval(userId, clientId, tokenScopes, autoApprovedScopes, new Date(accessTokenIssueDate));
    }

    return token;
}

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

/**
 * This method is implemented to support older API calls that assume the
 * presence of a token store/* w w w  .j a va 2s. c om*/
 */
@Override
public OAuth2AccessToken readAccessToken(String accessToken) {
    TokenValidation tokenValidation = validateToken(accessToken);
    Map<String, Object> claims = tokenValidation.getClaims();
    accessToken = tokenValidation.getJwt().getEncoded();

    // Expiry is verified by check_token
    CompositeAccessToken token = new CompositeAccessToken(accessToken);
    token.setTokenType(OAuth2AccessToken.BEARER_TYPE);
    Integer exp = (Integer) claims.get(EXP);
    if (null != exp) {
        token.setExpiration(new Date(exp.longValue() * 1000l));
    }

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);
    if (null != scopes && scopes.size() > 0) {
        token.setScope(new HashSet<>(scopes));
    }
    String clientId = (String) claims.get(CID);
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
    String userId = (String) claims.get(USER_ID);
    // Only check user access tokens
    if (null != userId) {
        @SuppressWarnings("unchecked")
        ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
        Set<String> autoApprovedScopes = getAutoApprovedScopes(claims.get(GRANT_TYPE), tokenScopes, client);
        checkForApproval(userId, clientId, tokenScopes, autoApprovedScopes);
    }

    return token;
}

From source file:org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor.java

/**
 * Extract the OAuth bearer token from a header.
 * /*from   w ww . jav a 2 s  .co m*/
 * @param request The request.
 * @return The token, or null if no OAuth authorization header was supplied.
 */
protected String extractHeaderToken(HttpServletRequest request) {
    Enumeration<String> headers = request.getHeaders("Authorization");
    while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
        String value = headers.nextElement();
        if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
            String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
            int commaIndex = authHeaderValue.indexOf(',');
            if (commaIndex > 0) {
                authHeaderValue = authHeaderValue.substring(0, commaIndex);
            }
            return authHeaderValue;
        }
    }

    return null;
}