List of usage examples for org.springframework.security.oauth2.provider.client BaseClientDetails setAutoApproveScopes
public void setAutoApproveScopes(Collection<String> autoApproveScopes)
From source file:com.example.ClientDetailsController.java
@PostMapping("/clients") public String add(Principal user) { BaseClientDetails client = new BaseClientDetails(strings.generate(), null, "openid,cloud_controller.read,cloud_controller.write", "password,authorization_code,refresh_token", "ROLE_CLIENT"); client.setClientSecret(strings.generate()); client.setAutoApproveScopes(Arrays.asList("true")); clients.addClientDetails(client);/*from ww w . j av a 2 s . c om*/ template.update("INSERT into user_client_details (username, client_id) values (?,?)", user.getName(), client.getClientId()); return "redirect:/clients"; }
From source file:oauth2.authentication.clients.ClientDetailsBuilder.java
public ClientDetails build() { BaseClientDetails client = new BaseClientDetails(); client.setClientId(clientId);//from ww w. j a va2 s. co m client.setClientSecret(clientSecret); client.setRegisteredRedirectUri(redirectUris.build()); client.setAuthorizedGrantTypes(authorizedGrantTypes.build()); client.setScope(scopes.build()); client.setAutoApproveScopes(autoApprovedScopes.build()); client.setResourceIds(resourceIds.build()); client.setAuthorities(authorities.build()); client.setAccessTokenValiditySeconds(accessTokenValiditySeconds); client.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds); return client; }
From source file:org.meruvian.yama.web.security.oauth.DefaultClientDetailsService.java
@Override public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException { Application application = null;/*from w w w. ja v a 2s .co m*/ if (defaultOauthApplications.containsKey(clientId)) { application = defaultOauthApplications.get(clientId); } else { application = applicationRepository.findById(clientId); } if (application == null) return null; BaseClientDetails details = new BaseClientDetails(); details.setClientId(application.getId()); details.setClientSecret(application.getSecret()); details.setAuthorizedGrantTypes(authorizedGrantTypes); details.setScope(scopes); details.setResourceIds(resourceIds); details.setRegisteredRedirectUri(application.getRegisteredRedirectUris()); if (application.isAutoApprove()) details.setAutoApproveScopes(Arrays.asList("true")); details.setAccessTokenValiditySeconds(application.getAccessTokenValiditySeconds()); details.setRefreshTokenValiditySeconds(application.getRefreshTokenValiditySeconds()); return details; }
From source file:com.cedac.security.oauth2.provider.client.MongoClientDetailsService.java
@SuppressWarnings("unchecked") private ClientDetails toClientDetails(DBObject dbo) { final String clientId = (String) dbo.get(clientIdFieldName); final String resourceIds = collectionToCommaDelimitedString((Collection) dbo.get(resourceIdsFieldName)); final String scopes = collectionToCommaDelimitedString((Collection) dbo.get(scopeFieldName)); final String grantTypes = collectionToCommaDelimitedString( (Collection) dbo.get(authorizedGrantTypesFieldName)); final String authorities = collectionToCommaDelimitedString((Collection) dbo.get(authoritiesFieldName)); final String redirectUris = collectionToCommaDelimitedString( (Collection) dbo.get(registeredRedirectUrisFieldName)); BaseClientDetails clientDetails = new BaseClientDetails(clientId, resourceIds, scopes, grantTypes, authorities, redirectUris);//from www . java 2 s .c om clientDetails.setClientSecret((String) dbo.get(clientSecretFieldName)); clientDetails.setAccessTokenValiditySeconds((Integer) dbo.get(accessTokenValidityFieldName)); clientDetails.setRefreshTokenValiditySeconds((Integer) dbo.get(refreshTokenValidityFieldName)); Object autoApprove = dbo.get(autoApproveFieldName); if (autoApprove != null) { if (autoApprove instanceof String) { clientDetails.setAutoApproveScopes(Collections.singleton((String) autoApprove)); } else { clientDetails.setAutoApproveScopes((Collection<String>) dbo.get(autoApproveFieldName)); } } DBObject additionalInfo = (DBObject) dbo.get(additionalInformationFieldName); if (additionalInfo != null) { for (String key : additionalInfo.keySet()) { clientDetails.addAdditionalInformation(key, additionalInfo.get(key)); } } return clientDetails; }
From source file:org.cloudfoundry.identity.uaa.client.ClientAdminEndpoints.java
private ClientDetails syncWithExisting(ClientDetails existing, ClientDetails input) { BaseClientDetails details = new BaseClientDetails(input); if (input instanceof BaseClientDetails) { BaseClientDetails baseInput = (BaseClientDetails) input; if (baseInput.getAutoApproveScopes() != null) { details.setAutoApproveScopes(baseInput.getAutoApproveScopes()); } else {/*from w ww . j a v a 2 s . c om*/ details.setAutoApproveScopes(new HashSet<String>()); if (existing instanceof BaseClientDetails) { BaseClientDetails existingDetails = (BaseClientDetails) existing; if (existingDetails.getAutoApproveScopes() != null) { for (String scope : existingDetails.getAutoApproveScopes()) { details.getAutoApproveScopes().add(scope); } } } } } if (details.getAccessTokenValiditySeconds() == null) { details.setAccessTokenValiditySeconds(existing.getAccessTokenValiditySeconds()); } if (details.getRefreshTokenValiditySeconds() == null) { details.setRefreshTokenValiditySeconds(existing.getRefreshTokenValiditySeconds()); } if (details.getAuthorities() == null || details.getAuthorities().isEmpty()) { details.setAuthorities(existing.getAuthorities()); } if (details.getAuthorizedGrantTypes() == null || details.getAuthorizedGrantTypes().isEmpty()) { details.setAuthorizedGrantTypes(existing.getAuthorizedGrantTypes()); } if (details.getRegisteredRedirectUri() == null || details.getRegisteredRedirectUri().isEmpty()) { details.setRegisteredRedirectUri(existing.getRegisteredRedirectUri()); } if (details.getResourceIds() == null || details.getResourceIds().isEmpty()) { details.setResourceIds(existing.getResourceIds()); } if (details.getScope() == null || details.getScope().isEmpty()) { details.setScope(existing.getScope()); } Map<String, Object> additionalInformation = new HashMap<String, Object>( existing.getAdditionalInformation()); additionalInformation.putAll(input.getAdditionalInformation()); for (String key : Collections.unmodifiableSet(additionalInformation.keySet())) { if (additionalInformation.get(key) == null) { additionalInformation.remove(key); } } details.setAdditionalInformation(additionalInformation); return details; }
From source file:org.cloudfoundry.identity.uaa.client.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()); }/*from ww w . j ava 2 s. c om*/ } 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()); } checkRequestedGrantTypes(requestedGrantTypes); 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() || securityContextAccessor.getScopes().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; }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void refreshAccessToken_withClient_withAutoApproveField() throws Exception { String clientId = "testclient" + generator.generate(); BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope", "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI); clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user")); clientDetails.setClientSecret("secret"); clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope")); clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa")); clientDetailsService.addClientDetails(clientDetails); String username = "testuser" + generator.generate(); String userScopes = "uaa.user,other.scope"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); MvcResult result = getMockMvc()// ww w . j a va 2s. com .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code") .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)) .andExpect(status().isFound()).andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map query = splitQuery(url); String code = ((List<String>) query.get("code")).get(0); state = ((List<String>) query.get("state")).get(0); MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token") .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).accept(MediaType.APPLICATION_JSON_VALUE) .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "authorization_code") .param(OAuth2Utils.CLIENT_ID, clientId).param("client_secret", "secret").param("code", code) .param("state", state); MvcResult mvcResult = getMockMvc().perform(oauthTokenPost).andReturn(); OAuth2RefreshToken refreshToken = JsonUtils .readValue(mvcResult.getResponse().getContentAsString(), CompositeAccessToken.class) .getRefreshToken(); MockHttpServletRequestBuilder postForRefreshToken = post("/oauth/token") .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes()))) .param(GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken.getValue()); getMockMvc().perform(postForRefreshToken).andExpect(status().isOk()); }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void authorizeEndpointWithPromptNone_WhenNotAuthenticated() throws Exception { String clientId = "testclient" + generator.generate(); BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope", "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI); clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user")); clientDetails.setClientSecret("secret"); clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope")); clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa")); clientDetailsService.addClientDetails(clientDetails); MockHttpSession session = new MockHttpSession(); String state = generator.generate(); MvcResult result = getMockMvc()/*w w w .j av a2 s . c o m*/ .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code") .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI) .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE)) .andExpect(status().isFound()).andExpect(cookie().maxAge("Current-User", 0)).andReturn(); String url = result.getResponse().getHeader("Location"); assertEquals(UaaUrlUtils.addQueryParameter(TEST_REDIRECT_URI, "error", "login_required"), url); }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testAuthorizeEndpointWithPromptNone_Authenticated() throws Exception { String clientId = "testclient" + generator.generate(); BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope", "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI); clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user")); clientDetails.setClientSecret("secret"); clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope")); clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa")); clientDetailsService.addClientDetails(clientDetails); String username = "testuser" + generator.generate(); String userScopes = "uaa.user,other.scope"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); MvcResult result = getMockMvc()//from w w w .j a va 2 s.c o m .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code") .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId) .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI) .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE)) .andExpect(status().isFound()).andReturn(); String url = result.getResponse().getHeader("Location"); assertThat(url, containsString(TEST_REDIRECT_URI)); }
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 ww. j av 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; }