Example usage for org.springframework.security.oauth2.provider.client BaseClientDetails getClientSecret

List of usage examples for org.springframework.security.oauth2.provider.client BaseClientDetails getClientSecret

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider.client BaseClientDetails getClientSecret.

Prototype

@org.codehaus.jackson.annotate.JsonIgnore
    @com.fasterxml.jackson.annotation.JsonIgnore
    public String getClientSecret() 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void revokeOtherClientToken() throws Exception {
    String resourceClientId = generator.generate();
    BaseClientDetails resourceClient = new BaseClientDetails(resourceClientId, "", "uaa.resource",
            "client_credentials,password", "uaa.resource");
    resourceClient.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, resourceClient);

    BaseClientDetails client = new BaseClientDetails(generator.generate(), "", "openid",
            "client_credentials,password", "tokens.revoke");
    client.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, client);

    //this is the token we will revoke
    String revokeAccessToken = getClientCredentialsOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), "tokens.revoke", null, false);

    String tokenToBeRevoked = getClientCredentialsOAuthAccessToken(getMockMvc(), resourceClientId,
            resourceClient.getClientSecret(), null, null, true);

    getMockMvc().perform(delete("/oauth/token/revoke/" + tokenToBeRevoked).header("Authorization",
            "Bearer " + revokeAccessToken)).andExpect(status().isOk());

    try {/*from  ww  w. j a  v  a  2s . c o m*/
        tokenProvisioning.retrieve(tokenToBeRevoked);
        fail("Token should have been deleted");
    } catch (EmptyResultDataAccessException e) {
        //expected
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void revokeOtherClientTokenForbidden() throws Exception {
    String resourceClientId = generator.generate();
    BaseClientDetails resourceClient = new BaseClientDetails(resourceClientId, "", "uaa.resource",
            "client_credentials,password", "uaa.resource");
    resourceClient.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, resourceClient);

    BaseClientDetails client = new BaseClientDetails(generator.generate(), "", "openid",
            "client_credentials,password", null);
    client.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, client);

    //this is the token we will revoke
    String revokeAccessToken = getClientCredentialsOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), null, null, false);

    String tokenToBeRevoked = getClientCredentialsOAuthAccessToken(getMockMvc(), resourceClientId,
            resourceClient.getClientSecret(), null, null, true);

    getMockMvc().perform(delete("/oauth/token/revoke/" + tokenToBeRevoked).header("Authorization",
            "Bearer " + revokeAccessToken)).andExpect(status().isForbidden());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void test_Revoke_Client_And_User_Tokens() throws Exception {
    BaseClientDetails client = getAClientWithClientsRead();
    BaseClientDetails otherClient = getAClientWithClientsRead();

    //this is the token we will revoke
    String readClientsToken = getClientCredentialsOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), null, null);

    //this is the token from another client
    String otherReadClientsToken = getClientCredentialsOAuthAccessToken(getMockMvc(), otherClient.getClientId(),
            otherClient.getClientSecret(), null, null);

    //ensure our token works
    getMockMvc().perform(get("/oauth/clients").header("Authorization", "Bearer " + readClientsToken))
            .andExpect(status().isOk());

    //ensure we can't get to the endpoint without authentication
    getMockMvc().perform(get("/oauth/token/revoke/client/" + client.getClientId()))
            .andExpect(status().isUnauthorized());

    //ensure we can't get to the endpoint without correct scope
    getMockMvc().perform(get("/oauth/token/revoke/client/" + client.getClientId()).header("Authorization",
            "Bearer " + otherReadClientsToken)).andExpect(status().isForbidden());

    //ensure that we have the correct error for invalid client id
    getMockMvc().perform(get("/oauth/token/revoke/client/notfound" + generator.generate())
            .header("Authorization", "Bearer " + adminToken)).andExpect(status().isNotFound());

    //we revoke the tokens for that client
    getMockMvc().perform(get("/oauth/token/revoke/client/" + client.getClientId()).header("Authorization",
            "Bearer " + adminToken)).andExpect(status().isOk());

    //we should fail attempting to use the token
    getMockMvc().perform(get("/oauth/clients").header("Authorization", "Bearer " + readClientsToken))
            .andExpect(status().isUnauthorized())
            .andExpect(content().string(containsString("\"error\":\"invalid_token\"")));

    ScimUser user = new ScimUser(null, generator.generate(), "Given Name", "Family Name");
    user.setPrimaryEmail(user.getUserName() + "@test.org");
    user.setPassword("password");

    user = createUser(getMockMvc(), adminToken, user);
    user.setPassword("password");

    String userInfoToken = getUserOAuthAccessToken(getMockMvc(), client.getClientId(), client.getClientSecret(),
            user.getUserName(), user.getPassword(), "openid");

    //ensure our token works
    getMockMvc().perform(get("/userinfo").header("Authorization", "Bearer " + userInfoToken))
            .andExpect(status().isOk());

    //we revoke the tokens for that user
    getMockMvc().perform(get("/oauth/token/revoke/user/" + user.getId() + "notfound").header("Authorization",
            "Bearer " + adminToken)).andExpect(status().isNotFound());

    //we revoke the tokens for that user
    getMockMvc().perform(//from w w w.  j a va2  s  . c  om
            get("/oauth/token/revoke/user/" + user.getId()).header("Authorization", "Bearer " + adminToken))
            .andExpect(status().isOk());

    getMockMvc().perform(get("/userinfo").header("Authorization", "Bearer " + userInfoToken))
            .andExpect(status().isUnauthorized())
            .andExpect(content().string(containsString("\"error\":\"invalid_token\"")));

}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static ZoneScimInviteData createZoneForInvites(MockMvc mockMvc, ApplicationContext context,
        String clientId, String redirectUri) throws Exception {
    RandomValueStringGenerator generator = new RandomValueStringGenerator();
    String superAdmin = getClientCredentialsOAuthAccessToken(mockMvc, "admin", "adminsecret", "", null);
    IdentityZoneCreationResult zone = utils()
            .createOtherIdentityZoneAndReturnResult(generator.generate().toLowerCase(), mockMvc, context, null);
    BaseClientDetails appClient = new BaseClientDetails("app", "", "scim.invite",
            "client_credentials,password,authorization_code",
            "uaa.admin,clients.admin,scim.write,scim.read,scim.invite", redirectUri);
    appClient.setClientSecret("secret");
    appClient = utils().createClient(mockMvc, zone.getZoneAdminToken(), appClient, zone.getIdentityZone());
    appClient.setClientSecret("secret");
    String adminToken = utils().getClientCredentialsOAuthAccessToken(mockMvc, appClient.getClientId(),
            appClient.getClientSecret(), "", zone.getIdentityZone().getSubdomain());

    String username = new RandomValueStringGenerator().generate().toLowerCase() + "@example.com";
    ScimUser user = new ScimUser(clientId, username, "given-name", "family-name");
    user.setPrimaryEmail(username);//  ww  w . j av  a 2s  .co m
    user.setPassword("password");
    user = createUserInZone(mockMvc, adminToken, user, zone.getIdentityZone().getSubdomain());
    user.setPassword("password");

    ScimGroup group = new ScimGroup("scim.invite");
    group.setMembers(Arrays.asList(new ScimGroupMember(user.getId(), USER, Arrays.asList(MEMBER))));

    return new ZoneScimInviteData(adminToken, zone, appClient, superAdmin);
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityProviderEndpointsMockMvcTests.java

@Test
public void testRetrieveIdpInZoneWithInsufficientScopes() throws Exception {
    BaseClientDetails client = getBaseClientDetails();

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.write");

    String originKey = RandomStringUtils.randomAlphabetic(6);
    IdentityProvider newIdp = MultitenancyFixture.identityProvider(originKey, IdentityZone.getUaa().getId());
    newIdp = createIdentityProvider(null, newIdp, accessToken, status().isCreated());

    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers/" + newIdp.getId())
            .header("Authorization", "Bearer" + adminToken).contentType(APPLICATION_JSON);

    getMockMvc().perform(requestBuilder).andExpect(status().isForbidden());
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityProviderEndpointsMockMvcTests.java

public String setUpAccessToken() throws Exception {
    String clientId = RandomStringUtils.randomAlphabetic(6);
    BaseClientDetails client = new BaseClientDetails(clientId, null, "idps.write", "password", null);
    client.setClientSecret("test-client-secret");
    mockMvcUtils.createClient(getMockMvc(), adminToken, client);

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.write");
    return mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(), client.getClientSecret(),
            user.getUserName(), "secr3T", "idps.write");
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityZoneSwitchingFilterMockMvcTest.java

@Test
public void testNoSwitching() throws Exception {

    final String clientId = UUID.randomUUID().toString();
    BaseClientDetails client = new BaseClientDetails(clientId, null, null, "client_credentials", null);
    client.setClientSecret("secret");

    getMockMvc().perform(/* w w w .ja  v a2 s .com*/
            post("/oauth/clients").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client)))
            .andExpect(status().isCreated());

    getMockMvc()
            .perform(get("/oauth/token?grant_type=client_credentials").header("Authorization",
                    "Basic " + new String(Base64
                            .encodeBase64((client.getClientId() + ":" + client.getClientSecret()).getBytes()))))
            .andExpect(status().isOk());
}

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

private void addNewClients() throws Exception {
    for (String clientId : clients.keySet()) {
        Map<String, Object> map = clients.get(clientId);
        BaseClientDetails client = new BaseClientDetails(clientId, (String) map.get("resource-ids"),
                (String) map.get("scope"), (String) map.get("authorized-grant-types"),
                (String) map.get("authorities"), (String) map.get("redirect-uri"));
        client.setClientSecret((String) map.get("secret"));
        Integer validity = (Integer) map.get("access-token-validity");
        Boolean override = (Boolean) map.get("override");
        if (override == null) {
            override = defaultOverride;//from   ww w  .  j  a  va2s  .  c om
        }
        Map<String, Object> info = new HashMap<String, Object>(map);
        if (validity != null) {
            client.setAccessTokenValiditySeconds(validity);
        }
        validity = (Integer) map.get("refresh-token-validity");
        if (validity != null) {
            client.setRefreshTokenValiditySeconds(validity);
        }
        // UAA does not use the resource ids in client registrations
        client.setResourceIds(Collections.singleton("none"));
        if (client.getScope().isEmpty()) {
            client.setScope(Collections.singleton("uaa.none"));
        }
        if (client.getAuthorities().isEmpty()) {
            client.setAuthorities(Collections.singleton(UaaAuthority.UAA_NONE));
        }
        if (client.getAuthorizedGrantTypes().contains("authorization_code")) {
            client.getAuthorizedGrantTypes().add("refresh_token");
        }
        for (String key : Arrays.asList("resource-ids", "scope", "authorized-grant-types", "authorities",
                "redirect-uri", "secret", "id", "override", "access-token-validity",
                "refresh-token-validity")) {
            info.remove(key);
        }
        client.setAdditionalInformation(info);
        try {
            clientRegistrationService.addClientDetails(client);
        } catch (ClientAlreadyExistsException e) {
            if (override == null || override) {
                logger.debug("Overriding client details for " + clientId);
                clientRegistrationService.updateClientDetails(client);
                if (StringUtils.hasText(client.getClientSecret())) {
                    clientRegistrationService.updateClientSecret(clientId, client.getClientSecret());
                }
            } else {
                // ignore it
                logger.debug(e.getMessage());
            }
        }
    }
}

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

private ClientDetails validateClient(ClientDetails prototype, boolean create) {

    BaseClientDetails client = new BaseClientDetails(prototype);

    client.setAdditionalInformation(prototype.getAdditionalInformation());

    String clientId = client.getClientId();
    if (create && reservedClientIds.contains(clientId)) {
        throw new InvalidClientDetailsException("Not allowed: " + clientId + " is a reserved client_id");
    }/*from w  w  w.  ja v  a  2 s  . co m*/

    Set<String> requestedGrantTypes = client.getAuthorizedGrantTypes();

    if (requestedGrantTypes.isEmpty()) {
        throw new InvalidClientDetailsException(
                "An authorized grant type must be provided. Must be one of: " + VALID_GRANTS.toString());
    }
    for (String grant : requestedGrantTypes) {
        if (!VALID_GRANTS.contains(grant)) {
            throw new InvalidClientDetailsException(
                    grant + " is not an allowed grant type. Must be one of: " + VALID_GRANTS.toString());
        }
    }

    if ((requestedGrantTypes.contains("authorization_code") || requestedGrantTypes.contains("password"))
            && !requestedGrantTypes.contains("refresh_token")) {
        logger.debug("requested grant type missing refresh_token: " + clientId);

        requestedGrantTypes.add("refresh_token");
    }

    if (!securityContextAccessor.isAdmin()) {

        // Not admin, so be strict with grant types and scopes
        for (String grant : requestedGrantTypes) {
            if (NON_ADMIN_INVALID_GRANTS.contains(grant)) {
                throw new InvalidClientDetailsException(
                        grant + " is not an allowed grant type for non-admin caller.");
            }
        }

        if (requestedGrantTypes.contains("implicit") && requestedGrantTypes.contains("authorization_code")) {
            throw new InvalidClientDetailsException(
                    "Not allowed: implicit grant type is not allowed together with authorization_code");
        }

        String callerId = securityContextAccessor.getClientId();
        if (callerId != null) {

            // New scopes are allowed if they are for the caller or the new
            // client.
            String callerPrefix = callerId + ".";
            String clientPrefix = clientId + ".";

            ClientDetails caller = clientDetailsService.retrieve(callerId);
            Set<String> validScope = caller.getScope();
            for (String scope : client.getScope()) {
                if (scope.startsWith(callerPrefix) || scope.startsWith(clientPrefix)) {
                    // Allowed
                    continue;
                }
                if (!validScope.contains(scope)) {
                    throw new InvalidClientDetailsException(scope + " is not an allowed scope for caller="
                            + callerId + ". Must have prefix in [" + callerPrefix + "," + clientPrefix
                            + "] or be one of: " + validScope.toString());
                }
            }

        } else { // No client caller. Shouldn't happen in practice, but let's
                 // be defensive

            // New scopes are allowed if they are for the caller or the new
            // client.
            String clientPrefix = clientId + ".";

            for (String scope : client.getScope()) {
                if (!scope.startsWith(clientPrefix)) {
                    throw new InvalidClientDetailsException(
                            scope + " is not an allowed scope for null caller and client_id=" + clientId
                                    + ". Must start with '" + clientPrefix + "'");
                }
            }
        }

        Set<String> validAuthorities = new HashSet<String>(NON_ADMIN_VALID_AUTHORITIES);
        if (requestedGrantTypes.contains("client_credentials")) {
            // If client_credentials is used then the client might be a
            // resource server
            validAuthorities.add("uaa.resource");
        }

        for (String authority : AuthorityUtils.authorityListToSet(client.getAuthorities())) {
            if (!validAuthorities.contains(authority)) {
                throw new InvalidClientDetailsException(authority + " is not an allowed authority for caller="
                        + callerId + ". Must be one of: " + validAuthorities.toString());
            }
        }

    }

    if (client.getAuthorities().isEmpty()) {
        client.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("uaa.none"));
    }

    // The UAA does not allow or require resource ids to be registered
    // because they are determined dynamically
    client.setResourceIds(Collections.singleton("none"));

    if (client.getScope().isEmpty()) {
        client.setScope(Collections.singleton("uaa.none"));
    }

    if (requestedGrantTypes.contains("implicit")) {
        if (StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException("Implicit grant should not have a client_secret");
        }
    }
    if (create) {
        // Only check for missing secret if client is being created.
        if ((requestedGrantTypes.contains("client_credentials")
                || requestedGrantTypes.contains("authorization_code"))
                && !StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException(
                    "Client secret is required for client_credentials and authorization_code grant types");
        }
    }

    return client;

}

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

public ClientDetails validate(ClientDetails prototype, boolean create, boolean checkAdmin)
        throws InvalidClientDetailsException {

    BaseClientDetails client = new BaseClientDetails(prototype);
    if (prototype instanceof BaseClientDetails) {
        Set<String> scopes = ((BaseClientDetails) prototype).getAutoApproveScopes();
        if (scopes != null) {
            client.setAutoApproveScopes(((BaseClientDetails) prototype).getAutoApproveScopes());
        }/*w  w w.j  a  v a 2 s .c  o m*/
    }

    client.setAdditionalInformation(prototype.getAdditionalInformation());

    String clientId = client.getClientId();
    if (create && reservedClientIds.contains(clientId)) {
        throw new InvalidClientDetailsException("Not allowed: " + clientId + " is a reserved client_id");
    }

    Set<String> requestedGrantTypes = client.getAuthorizedGrantTypes();

    if (requestedGrantTypes.isEmpty()) {
        throw new InvalidClientDetailsException(
                "An authorized grant type must be provided. Must be one of: " + VALID_GRANTS.toString());
    }
    for (String grant : requestedGrantTypes) {
        if (!VALID_GRANTS.contains(grant)) {
            throw new InvalidClientDetailsException(
                    grant + " is not an allowed grant type. Must be one of: " + VALID_GRANTS.toString());
        }
    }

    if ((requestedGrantTypes.contains("authorization_code") || requestedGrantTypes.contains("password"))
            && !requestedGrantTypes.contains("refresh_token")) {
        logger.debug("requested grant type missing refresh_token: " + clientId);

        requestedGrantTypes.add("refresh_token");
    }

    if (checkAdmin && !(securityContextAccessor.isAdmin() || UaaStringUtils
            .getStringsFromAuthorities(securityContextAccessor.getAuthorities()).contains("clients.admin"))) {

        // Not admin, so be strict with grant types and scopes
        for (String grant : requestedGrantTypes) {
            if (NON_ADMIN_INVALID_GRANTS.contains(grant)) {
                throw new InvalidClientDetailsException(
                        grant + " is not an allowed grant type for non-admin caller.");
            }
        }

        if (requestedGrantTypes.contains("implicit") && requestedGrantTypes.contains("authorization_code")) {
            throw new InvalidClientDetailsException(
                    "Not allowed: implicit grant type is not allowed together with authorization_code");
        }

        String callerId = securityContextAccessor.getClientId();
        ClientDetails caller = null;
        try {
            caller = clientDetailsService.retrieve(callerId);
        } catch (Exception e) {
            // best effort to get the caller, but the caller might not belong to this zone.
        }
        if (callerId != null && caller != null) {

            // New scopes are allowed if they are for the caller or the new
            // client.
            String callerPrefix = callerId + ".";
            String clientPrefix = clientId + ".";

            Set<String> validScope = caller.getScope();
            for (String scope : client.getScope()) {
                if (scope.startsWith(callerPrefix) || scope.startsWith(clientPrefix)) {
                    // Allowed
                    continue;
                }
                if (!validScope.contains(scope)) {
                    throw new InvalidClientDetailsException(scope + " is not an allowed scope for caller="
                            + callerId + ". Must have prefix in [" + callerPrefix + "," + clientPrefix
                            + "] or be one of: " + validScope.toString());
                }
            }

        } else {
            // New scopes are allowed if they are for the caller or the new
            // client.
            String clientPrefix = clientId + ".";

            for (String scope : client.getScope()) {
                if (!scope.startsWith(clientPrefix)) {
                    throw new InvalidClientDetailsException(
                            scope + " is not an allowed scope for null caller and client_id=" + clientId
                                    + ". Must start with '" + clientPrefix + "'");
                }
            }
        }

        Set<String> validAuthorities = new HashSet<String>(NON_ADMIN_VALID_AUTHORITIES);
        if (requestedGrantTypes.contains("client_credentials")) {
            // If client_credentials is used then the client might be a
            // resource server
            validAuthorities.add("uaa.resource");
        }

        for (String authority : AuthorityUtils.authorityListToSet(client.getAuthorities())) {
            if (!validAuthorities.contains(authority)) {
                throw new InvalidClientDetailsException(authority + " is not an allowed authority for caller="
                        + callerId + ". Must be one of: " + validAuthorities.toString());
            }
        }

    }

    if (client.getAuthorities().isEmpty()) {
        client.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("uaa.none"));
    }

    // The UAA does not allow or require resource ids to be registered
    // because they are determined dynamically
    client.setResourceIds(Collections.singleton("none"));

    if (client.getScope().isEmpty()) {
        client.setScope(Collections.singleton("uaa.none"));
    }

    if (requestedGrantTypes.contains("implicit")) {
        if (StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException("Implicit grant should not have a client_secret");
        }
    }
    if (create) {
        // Only check for missing secret if client is being created.
        if ((requestedGrantTypes.contains("client_credentials")
                || requestedGrantTypes.contains("authorization_code"))
                && !StringUtils.hasText(client.getClientSecret())) {
            throw new InvalidClientDetailsException(
                    "Client secret is required for client_credentials and authorization_code grant types");
        }
    }

    return client;

}