public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { ClientDetails clientDetails; try { clientDetails = clientDetailsService.loadClientByClientId(username); } catch (NoSuchClientException e) { throw new UsernameNotFoundException(e.getMessage(), e); } String clientSecret = clientDetails.getClientSecret(); if (clientSecret== null || clientSecret.trim().length()==0) { clientSecret = emptyPassword; } return new User(username, clientSecret, clientDetails.getAuthorities()); }
public OAuth2Request createOAuth2Request(ClientDetails client) { Map<String, String> requestParameters = getRequestParameters(); HashMap<String, String> modifiable = new HashMap<String, String>(requestParameters); // Remove password if present to prevent leaks modifiable.remove("password"); modifiable.remove("client_secret"); // Add grant type so it can be retrieved from OAuth2Request modifiable.put("grant_type", grantType); return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(), client.getResourceIds(), null, null, null); }
/** * Convenience method to set resourceIds and authorities on this request by * inheriting from a ClientDetails object. * * @param clientDetails */ public void setResourceIdsAndAuthoritiesFromClientDetails(ClientDetails clientDetails) { setResourceIds(clientDetails.getResourceIds()); setAuthorities(clientDetails.getAuthorities()); }
protected Set<String> extractScopes(Map<String, String> requestParameters, ClientDetails clientDetails) { boolean clientCredentials = GRANT_TYPE_CLIENT_CREDENTIALS.equals(requestParameters.get(GRANT_TYPE)); Set<String> scopes = OAuth2Utils.parseParameterList(requestParameters.get(OAuth2Utils.SCOPE)); if ((scopes == null || scopes.isEmpty())) { // If no scopes are specified in the incoming data, use the default values registered with the client // (the spec allows us to choose between this option and rejecting the request completely, so we'll take the // least obnoxious choice as a default). if (clientCredentials) { Set<String> authorities = new HashSet<>(); for (GrantedAuthority a : clientDetails.getAuthorities()) { authorities.add(a.getAuthority()); } scopes = authorities; } else { scopes = clientDetails.getScope(); } } if (!clientCredentials) { Set<String> userScopes = getUserScopes(); scopes = intersectScopes(scopes, clientDetails.getScope(), userScopes); } return scopes; }
@Override public AuditEvent getAuditEvent() { ClientDetails clientDetails = Optional.ofNullable(getClient()).orElse(nonExistent); Map<String, Object> auditData = new HashMap(); auditData.put("scopes", clientDetails.getScope()); List<String> authorities = clientDetails .getAuthorities() .stream() .map(a -> a.getAuthority()) .collect(Collectors.toList()); auditData.put("authorities", authorities); return createAuditRecord( clientDetails.getClientId(), getAuditEventType(), getOrigin(getPrincipal()), JsonUtils.writeValueAsString(auditData) ); }
@Override public OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException { ClientDetails client = clientDetailsService.loadClientByClientId(getClientId(), IdentityZoneHolder.get().getId()); Set<String> scopes = new HashSet<>(); for (GrantedAuthority authority : client.getAuthorities()) { scopes.add(authority.getAuthority()); } Set<String> resourceIds = new HashSet<>(); resourceIds.add(OriginKeys.UAA); Map<String,String> requestParameters = new HashMap<>(); requestParameters.put(OAuth2Utils.CLIENT_ID, "login"); requestParameters.put(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS); OAuth2Request request = new OAuth2Request( requestParameters, "login", (Collection<? extends GrantedAuthority>)Collections.EMPTY_SET, true, scopes, resourceIds, null, new HashSet<>(), Collections.EMPTY_MAP); OAuth2Authentication authentication = new OAuth2Authentication(request, null); OAuth2AccessToken result = tokenServices.createAccessToken(authentication); oauth2Context.setAccessToken(result); return result; }
/** * Apply UAA rules to validate the requested scopes scope. For client credentials * grants the valid requested scopes are actually in * the authorities of the client. * */ public void validateParameters(Map<String, String> parameters, ClientDetails clientDetails) { if (parameters.containsKey("scope")) { Set<String> validScope = clientDetails.getScope(); if (GRANT_TYPE_CLIENT_CREDENTIALS.equals(parameters.get("grant_type"))) { validScope = AuthorityUtils.authorityListToSet(clientDetails.getAuthorities()); } Set<Pattern> validWildcards = constructWildcards(validScope); Set<String> scopes = OAuth2Utils.parseParameterList(parameters.get("scope")); for (String scope : scopes) { if (!matches(validWildcards, scope)) { throw new InvalidScopeException(scope + " is invalid. Please use a valid scope name in the request"); } } } }
public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException { if (GRANT_TYPE_CLIENT_CREDENTIALS.equalsIgnoreCase(authorizationRequest.getRequestParameters().get(OAuth2Utils.GRANT_TYPE))) { validateScope(authorizationRequest.getScope(), getAuthorities(client.getAuthorities()), false); } else { validateScope(authorizationRequest.getScope(), client.getScope(), true); } }
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { // read and load up the existing token try { String incomingAssertionValue = tokenRequest.getRequestParameters().get("assertion"); JWT assertion = JWTParser.parse(incomingAssertionValue); if (validator.isValid(assertion)) { // our validator says it's OK, time to make a token from it // the real work happens in the assertion factory and the token services return new OAuth2Authentication(assertionFactory.createOAuth2Request(client, tokenRequest, assertion), new JWTBearerAssertionAuthenticationToken(assertion, client.getAuthorities())); } else { logger.warn("Incoming assertion did not pass validator, rejecting"); return null; } } catch (ParseException e) { logger.warn("Unable to parse incoming assertion"); } // if we had made a token, we'd have returned it by now, so return null here to close out with no created token return null; }
@Override public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) { try { JWTClaimsSet claims = assertion.getJWTClaimsSet(); Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); Set<String> resources = Sets.newHashSet(claims.getAudience()); return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, scope, resources, null, null, null); } catch (ParseException e) { return null; } }
@Override public ClientDetails validate(ClientDetails clientDetails, Mode mode) throws InvalidClientDetailsException { if (Mode.CREATE.equals(mode) || Mode.MODIFY.equals(mode)) { for (String scope : clientDetails.getScope()) { if (uaaScopes.isUaaScope(scope)) { throw new InvalidClientDetailsException(scope+" is a restricted scope."); } } for (GrantedAuthority authority : clientDetails.getAuthorities()) { if (uaaScopes.isUaaScope(authority)) { throw new InvalidClientDetailsException(authority.getAuthority()+" is a restricted authority."); } } } return clientDetails; } }
public void validateScope(TokenRequest tokenRequest, ClientDetails client) throws InvalidScopeException { if (GRANT_TYPE_CLIENT_CREDENTIALS.equalsIgnoreCase(tokenRequest.getGrantType())) { validateScope(tokenRequest.getScope(), getAuthorities(client.getAuthorities()), false); } else if (GRANT_TYPE_USER_TOKEN.equalsIgnoreCase(tokenRequest.getGrantType())) { client = clientDetailsService.loadClientByClientId(tokenRequest.getRequestParameters().get(CLIENT_ID), IdentityZoneHolder.get().getId()); validateScope(tokenRequest.getScope(), client.getScope(), true); } else { validateScope(tokenRequest.getScope(), client.getScope(), true); } }
@Override public OAuth2Request createOAuth2Request(ClientDetails client) { OAuth2Request request = super.createOAuth2Request(client); return new OAuth2Request( request.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, request.getScope(), resourceIds, request.getRedirectUri(), responseTypes, request.getExtensions()); } }
private Object[] getFieldsForUpdate(ClientDetails clientDetails, String zoneId) { Map<String, Object> additionalInformation = new HashMap(clientDetails.getAdditionalInformation()); Collection<String> requiredGroups = (Collection<String>) additionalInformation.remove(REQUIRED_USER_GROUPS); String json; try { json = JsonUtils.writeValueAsString(additionalInformation); } catch (Exception e) { logger.warn("Could not serialize additional information: " + clientDetails, e); throw new InvalidDataAccessResourceUsageException("Could not serialize additional information:"+clientDetails.getClientId(), e); } return new Object[] { collectionToString(clientDetails.getResourceIds()), collectionToString(clientDetails.getScope()), collectionToString(clientDetails.getAuthorizedGrantTypes()), collectionToString(clientDetails.getRegisteredRedirectUri()), collectionToString(clientDetails.getAuthorities()), clientDetails.getAccessTokenValiditySeconds(), clientDetails.getRefreshTokenValiditySeconds(), json, getAutoApproveScopes(clientDetails), new Timestamp(System.currentTimeMillis()), collectionToString(requiredGroups), clientDetails.getClientId(), zoneId }; }
private Object[] getFieldsForUpdate(ClientDetails clientDetails) { String json = null; try { json = mapper.write(clientDetails.getAdditionalInformation()); } catch (Exception e) { logger.warn("Could not serialize additional information: " + clientDetails, e); } return new Object[] { clientDetails.getResourceIds() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getResourceIds()) : null, clientDetails.getScope() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getScope()) : null, clientDetails.getAuthorizedGrantTypes() != null ? StringUtils .collectionToCommaDelimitedString(clientDetails.getAuthorizedGrantTypes()) : null, clientDetails.getRegisteredRedirectUri() != null ? StringUtils .collectionToCommaDelimitedString(clientDetails.getRegisteredRedirectUri()) : null, clientDetails.getAuthorities() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getAuthorities()) : null, clientDetails.getAccessTokenValiditySeconds(), clientDetails.getRefreshTokenValiditySeconds(), json, getAutoApproveScopes(clientDetails), clientDetails.getClientId() }; }
assertEquals(validity, created.getRefreshTokenValiditySeconds()); assertSet((String) map.get("authorities"), Collections.emptySet(), created.getAuthorities(), GrantedAuthority.class);
public BaseClientDetails(ClientDetails prototype) { this(); setAccessTokenValiditySeconds(prototype.getAccessTokenValiditySeconds()); setRefreshTokenValiditySeconds(prototype .getRefreshTokenValiditySeconds()); setAuthorities(prototype.getAuthorities()); setAuthorizedGrantTypes(prototype.getAuthorizedGrantTypes()); setClientId(prototype.getClientId()); setClientSecret(prototype.getClientSecret()); setRegisteredRedirectUri(prototype.getRegisteredRedirectUri()); setScope(prototype.getScope()); setResourceIds(prototype.getResourceIds()); }
@Test void testPutClientModifyAuthorities() throws Exception { ClientDetails client = createClient(adminToken, "testClientForModifyAuthorities", SECRET, Collections.singleton("client_credentials")); BaseClientDetails modified = new BaseClientDetails(client); modified.setAuthorities(Collections.singleton((GrantedAuthority) () -> "newAuthority")); MockHttpServletRequestBuilder put = put("/oauth/clients/" + client.getClientId()) .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content(JsonUtils.writeValueAsString(modified)); mockMvc.perform(put).andExpect(status().isOk()).andReturn(); client = getClient(client.getClientId()); assertThat(client.getAuthorities(), iterableWithSize(1)); GrantedAuthority authority = Iterables.get(client.getAuthorities(), 0); assertEquals("newAuthority", authority.getAuthority()); }
@Test public void testCreateLimitedClient() { BaseClientDetails clientDetails = new BaseClientDetails("valid-client", null, "openid", "authorization_code,password", "uaa.resource"); clientDetails.setClientSecret("secret"); clientDetails.addAdditionalInformation(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); ClientDetails validatedClientDetails = zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE); assertEquals(clientDetails.getClientId(), validatedClientDetails.getClientId()); assertEquals(clientDetails.getScope(), validatedClientDetails.getScope()); assertEquals(clientDetails.getAuthorizedGrantTypes(), validatedClientDetails.getAuthorizedGrantTypes()); assertEquals(clientDetails.getAuthorities(), validatedClientDetails.getAuthorities()); assertEquals(Collections.singleton("none"), validatedClientDetails.getResourceIds()); assertEquals(Collections.singletonList(OriginKeys.UAA), validatedClientDetails.getAdditionalInformation().get(ALLOWED_PROVIDERS)); }
@Test public void testLoadingClientIdWithNoDetails() { int rowsInserted = jdbcTemplate.update(INSERT_SQL, "clientIdWithNoDetails", null, null, null, null, null, null, null, null, null, IdentityZoneHolder.get().getId(), new Timestamp(System.currentTimeMillis()), dbRequestedUserGroups ); assertEquals(1, rowsInserted); ClientDetails clientDetails = service .loadClientByClientId("clientIdWithNoDetails"); assertEquals("clientIdWithNoDetails", clientDetails.getClientId()); assertFalse(clientDetails.isSecretRequired()); assertNull(clientDetails.getClientSecret()); assertFalse(clientDetails.isScoped()); assertEquals(0, clientDetails.getScope().size()); assertEquals(2, clientDetails.getAuthorizedGrantTypes().size()); assertNull(clientDetails.getRegisteredRedirectUri()); assertEquals(0, clientDetails.getAuthorities().size()); assertEquals(null, clientDetails.getAccessTokenValiditySeconds()); assertEquals(null, clientDetails.getAccessTokenValiditySeconds()); }